简体   繁体   English

在python中读取文本文件

[英]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. 我们正在处理comp sci中的文件。 This program is supposed to find the highest grade in a certain .txt file that I named "File1.txt". 该程序应该在我命名为“ File1.txt”的某个.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? 这是因为我使用的是Mac,并且有另一种方法可以在OSX上通过python读取文件吗?

if it's Python 2, you probably want raw_input not input . 如果是Python 2,您可能希望不input raw_input

as a general rule, when developing a program it's a good idea, at the end of your except clause, to use raise . 通常,在开发程序时,在except子句的末尾使用raise是一个好主意。 this throws the original exception and shows you better what went wrong. 这会引发原始异常,并向您更好地说明出了什么问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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