Python alternative to fscanf C code
Question: I have some C code that works well:

    
    
    #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;
    }
    

data inside `EMPLOYEE.DAT`:

    
    
    Sunil 34 1250.50
    Sameer 21 1300.50
    rahul 34 1400.50
    

I'm having trouble translating this code to 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);
    

Is there any way to implement that in Python? Furthermore, what are Pythonic
alternatives of `exit()` & `EOF`?


Answer: Something like:

    
    
    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)
    

If you want to store the data in a structure, you can use the builtin `dict`
type (hash map)

    
    
    person = {'name': name, 'age': age, 'bs': bs}
    person['name'] # access data
    

Or you could define your own class:

    
    
    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
    

**EDIT**

Here's a version that handles the error if the file does not exist. And
returns an `exit` code.

    
    
    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)
    

