简体   繁体   中英

Reading text files in python

endofprogram=False 
try:
    filename=input("Enter filename: ")
    infile=open(filename,"r")
except IOError:
    print("Error reading file! Program ends here!")
    endofprogram=True
if endofprogram==False:
    highest=0.0
    for line in infile:
        line=line.strip('\n')
        if(line!="") and (line[0]!='#'):
            name,grade=line.split('\t')
            if(float(grade)>highest):
                highest=float(grade)

                hname=name
        record=(hname,highest)

        print(record)
        infile.close()

We're working on files in comp sci now. This program is supposed to find the highest grade in a certain .txt file that I named "File1.txt".

#fname lname grade
Charlie Watson  8
Alice Brown     8.5
#Comments

Francene Walk   9
Robert Wilson   7
Evelyn Stewart  10
Gordon Rogers   8.5  

So in order to access this file through the program we're supposed to have it in the same folder, as we were taught in class. But when I enter the correct file name as an input through the program I get the "Error reading file!" message displayed. Is this because I'm using a Mac and there's a different method to reading files through python on OSX?

if it's Python 2, you probably want raw_input not input .

as a general rule, when developing a program it's a good idea, at the end of your except clause, to use raise . this throws the original exception and shows you better what went wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM