Python 属性错误:';列表';对象没有属性';关闭';用于读取一个文件

Python 属性错误:';列表';对象没有属性';关闭';用于读取一个文件,python,Python,对于打开和读取1个文件,即使在添加close参数之后,也会出现错误。编写的代码如下: infilename = "Rate.txt" infile = open(infilename, "r").readlines() firstLine = infile.pop(0) #removes the header(first line) infile = infile[:-1]#removes the last line for line in infile: a = line.split(

对于打开和读取1个文件,即使在添加close参数之后,也会出现错误。编写的代码如下:

infilename = "Rate.txt"
infile = open(infilename, "r").readlines()
firstLine = infile.pop(0) #removes the header(first line)
infile = infile[:-1]#removes the last line
for line in infile:
    a = line.split()
    CheckNumeric = a[4]
    CheckNumeric1 = a[5]
    strfield = a[3]
infile.close()

infle
变量中存储的值不是文件对象,而是列表。因为您调用了
readlines
方法。

正在执行

infile = open(infilename, "r").readlines()
您已读取文件的行,并将列表指定给
infle
。但您尚未将该文件分配给变量

如果要显式关闭该文件:

someFile = open(infilename, "r")
infile = someFile.readlines()
...
someFile.close()
或者将
一起使用,自动关闭文件:

with open(infilename, "r") as someFile:
    infile = someFile.readlines()
    ....
print "the file here is closed"

通过执行
infle=open(infleName,“r”).readlines()
实际上已将
infle
指定为一个
列表,而不是一个打开的文件对象。垃圾收集器应该清理并关闭打开的文件,但更好的处理方法是使用块:

在上面的代码中,
with
块中缩进的所有内容都将在文件打开时执行。块结束后,文件将自动关闭

infile = open(infilename, "r")
# this resp. infile is a file object (where you can call the function close())

infile = open(infilename, "r").readlines()
# this resp. infile is a list object, because readlines() returns a list

仅此而已。

正如上面提到的@Ffisegydd一样,使用Python 2.5中引入的带有语句的。它将在嵌套代码块之后自动为您关闭文件。然而,如果异常也发生了,文件将在捕获异常之前关闭,非常方便

有关详细信息,请在上下文管理器上签出:
实际上,我使用上下文管理器来实现某种程度的可维护性。

我将使用以下更节省内存的代码:

infilename = "Rate.txt"
with open (infilename) as f:
   next(f) # Skip header
   dat = None
   for line in f:
        if dat: # Skip last line
            _, _, _, strfield, CheckNumeric,  CheckNumeric1 = dat.split()
        dat = line

.readlines()
使
infle
成为
列表
infle
不是文件的处理程序,是由
readlines
方法生成的
列表。您也可以使用my_list.pop()
infilename = "Rate.txt"
with open (infilename) as f:
   next(f) # Skip header
   dat = None
   for line in f:
        if dat: # Skip last line
            _, _, _, strfield, CheckNumeric,  CheckNumeric1 = dat.split()
        dat = line