繁体   English   中英

AttributeError:“列表”对象没有用于读取一个文件的属性“关闭”

[英]AttributeError: 'list' object has no attribute 'close' for reading one file

即使添加了close参数也要打开和读取1个文件,但它给出了错误。 编写的代码如下:

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()

通过执行infile = open(infilename, "r").readlines()您实际上已将infile分配为一个list ,而不是一个打开的文件对象。 垃圾收集器应清除打开的文件并为您关闭,但是更好的处理方法是使用with块:

infilename = "Rate.txt"
with open(infilename, "r") as infile:
    line_list = infile.readlines()

firstLine = line_list.pop(0) #removes the header(first line)
line_list = line_list[:-1]#removes the last line
for line in line_list:
    a = line.split()
    CheckNumeric = a[4]
    CheckNumeric1 = a[5]
    strfield = a[3]

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

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

在做

infile = open(infilename, "r").readlines()

您已经阅读了文件的各行,并将列表分配给infile 但是您尚未将文件分配给变量。

如果要显式关闭文件:

someFile = open(infilename, "r")
infile = someFile.readlines()
...
someFile.close()

或者使用with自动关闭该文件:

with open(infilename, "r") as someFile:
    infile = someFile.readlines()
    ....
print "the file here is closed"
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中引入的with语句 嵌套代码块之后,它将自动为您关闭文件。 但是,万一发生异常,该文件将在捕获异常之前关闭,非常方便。

有关更多信息,请在上下文管理器上签出: https : //docs.python.org/2/library/contextlib.html实际上,我利用上下文管理器来实现某种程度的可维护性。

我将使用以下内存效率更高的代码:

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

暂无
暂无

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

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