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?

1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

for line in f: would suffice to avoid reading the file all at once using f.readlines. It matches the behavior more closely anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.