2014-01-20 145 views
3

我有一些C代碼工作得很好:內EMPLOYEE.DATPython的替代FSCANF 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; 
} 

數據:

Sunil 34 1250.50 
Sameer 21 1300.50 
rahul 34 1400.50 

我有麻煩翻譯這段代碼的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中實現嗎?此外,什麼是Pythonic替代品exit() & EOF

+0

[在Python的sscanf]的可能的複製(https://stackoverflow.com/questions/2175080/sscanf-in-python) – dvb

回答

5

喜歡的東西:

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類型(散列圖)

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

或者你可以定義你自己的類:

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 

編輯

以下是處理錯誤(如果文件不存在)的版本。並返回一個exit的代碼。

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) 
+1

'用於在F線:'將足以避免讀取在文件中的所有一旦使用'f.readlines'。無論如何,它更貼近行爲。 –

+1

@ChronoKitsune你是對的,謝謝。 –

+1

@ user3207754看到我更新的答案 –