Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python alternative to fscanf C code

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?

like image 528
user3207754 Avatar asked Jan 20 '14 01:01

user3207754


People also ask

Is there a scanf () or sscanf () equivalent in python?

There is nothing as such for python. For simple input parsing, the easiest way is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float().

What is the replacement of scanf in Python?

Python does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though also more verbose, than scanf()format strings.

How do you use Sscanf in Python?

Python does not currently have a sscanf() equivalent. Regular expressions are generally more powerful, albeit more verbose, than scanf () strings. The table below shows some more or less equivalent mappings between scanf () format tokens and regular expressions.

What does fscanf do?

The fscanf() function reads data from the current position of the specified stream into the locations that are given by the entries in argument-list , if any. Each entry in argument-list must be a pointer to a variable with a type that corresponds to a type specifier in format-string .


1 Answers

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)
like image 115
Peter Gibson Avatar answered Oct 11 '22 04:10

Peter Gibson