5

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?

Jeff Bauer
  • 13,890
  • 9
  • 51
  • 73
user3207754
  • 87
  • 1
  • 1
  • 6

1 Answers1

6

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)
Peter Gibson
  • 19,086
  • 7
  • 60
  • 64
  • 1
    `for line in f:` would suffice to avoid reading the file all at once using `f.readlines`. It matches the behavior more closely anyway. –  Jan 20 '14 at 01:27