fscanf C代码的Python替代方案

fscanf C代码的Python替代方案,python,c,python-2.7,Python,C,Python 2.7,我有一些运行良好的C代码: #include<stdio.h> #include<stdlib.h> int main() { FILE *fp; struct emp { char name[40]; int age; float bs; }; struct emp e; fp=fopen("EMPLOYEE.DAT","r"); if(fp==NULL) {

我有一些运行良好的C代码:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE *fp;
    struct emp
    {
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    fp=fopen("EMPLOYEE.DAT","r");
    if(fp==NULL)
    {
        puts("Cannot open file";
        exit(1);
    }
    while(fscanf(f,"%s %d %f",&e.name,&e.age,&e.bs)!=EOF)
        printf("%s %d %f\n",e.name,e.age,e.bs);

    fclose(fp);
    return 0;
}
将此代码翻译为Python时遇到问题:

while(fscanf(f,"%s %d %f",&e.name,&e.age,&e.bs)!=EOF)
    printf("%s %d %f\n",e.name,e.age,e.bs);
有没有办法在Python中实现这一点?此外,什么是
exit()
EOF
的Pythonic替代方案?

类似于:

with open("EMPLOYEE.DAT") as f: # open the file for reading
    for line in f: # iterate over each line
        name, age, bs = line.split() # split it by whitespace
        age = int(age) # convert age from string to int
        bs = float(bs) # convert bs from string to float
        print(name, age, bs)
如果要将数据存储在结构中,可以使用内置的dict
type(哈希映射)

或者您可以定义自己的类:

class Employee(object):
    def __init__(self, name, age, bs):
        self.name = name
        self.age = age
        self.bs = bs

e = Employee(name, age, bs) # create an instance
e.name # access data
编辑

如果文件不存在,下面是一个处理错误的版本。并返回一个
退出
代码

import sys
try:
    with open("EMPLOYEE.DAT") as f:
        for line in f:
            name, age, bs = line.split()
            age = int(age)
            bs = float(bs)
            print(name, age, bs)
except IOError:
    print("Cannot open file")
    sys.exit(1)

对于f中的行:
足以避免使用
f.readlines
一次性读取文件。无论如何,它与行为的匹配度更高。可能是
class Employee(object):
    def __init__(self, name, age, bs):
        self.name = name
        self.age = age
        self.bs = bs

e = Employee(name, age, bs) # create an instance
e.name # access data
import sys
try:
    with open("EMPLOYEE.DAT") as f:
        for line in f:
            name, age, bs = line.split()
            age = int(age)
            bs = float(bs)
            print(name, age, bs)
except IOError:
    print("Cannot open file")
    sys.exit(1)