Python 关闭文件时出错
我正在运行Python2.6.5,部分代码涉及打开和读取文本文件。问题是我希望用来关闭文件的命令不起作用,我在读取时出错:Python 关闭文件时出错,python,Python,我正在运行Python2.6.5,部分代码涉及打开和读取文本文件。问题是我希望用来关闭文件的命令不起作用,我在读取时出错: AttributeError: 'str' object has no attribute 'close' 这源于: # Open header and data files to create a dictionary header = open("pathToHeader","rU") data = open(os.path.join(someFilePath,fil
AttributeError: 'str' object has no attribute 'close'
这源于:
# Open header and data files to create a dictionary
header = open("pathToHeader","rU")
data = open(os.path.join(someFilePath,fileName),"rU")
# Create the dictionary whose contents can be called by columns[header]
f = chain(h,data)
reader = csv.DictReader(f,fieldnames=h.read().strip('\n').split(','),delimiter=',')
for row in reader:
for (header,variable) in row.items():
columns[header].append(str(variable))
# Close the two files
header.close()
data.close()
从我到目前为止所查找的内容来看,这是关闭文件的正确命令。是因为我将open命令分配给一个变量,所以出现了问题吗?一旦我创建了字典,文件是否会自动关闭?您在内部
for
循环中重写了头文件。重命名它。您在内部中为
循环重写了标题。重命名它。您已经在for循环中重新定义了变量头
。您已经在for循环中重新定义了变量头
。您正在对字符串而不是文件对象调用close()
for (header,variable) in row.items():
最佳实践是将语句中的文件对象用作上下文管理器。这样,无论块如何结束,它们都会自动关闭:
with open("pathToHeader","rU") as header:
fieldnames = h.read().strip('\n').split(',')
data_file = os.path.join(someFilePath, fileName)
with open(data_file, "rU") as data:
reader = csv.DictReader(data, fieldnames)
for row in reader:
for key, variable in row.items():
columns[key].append(variable)
在此过程中,我对您的代码进行了一些重构。请注意,如果要读取所有的标题
,则在数据之前链接标题
没有什么意义。您调用的是字符串而不是文件对象上的close()
,因为您重复使用了名称标题
:
for (header,variable) in row.items():
最佳实践是将语句中的文件对象用作上下文管理器。这样,无论块如何结束,它们都会自动关闭:
with open("pathToHeader","rU") as header:
fieldnames = h.read().strip('\n').split(',')
data_file = os.path.join(someFilePath, fileName)
with open(data_file, "rU") as data:
reader = csv.DictReader(data, fieldnames)
for row in reader:
for key, variable in row.items():
columns[key].append(variable)
在此过程中,我对您的代码进行了一些重构。请注意,在代码< >代码>数据> >代码>之前,链接“代码>数据头<代码>没有什么意义。无论如何,您将要阅读所有的<代码>标题>代码>。如果不是,什么是<代码>页眉<代码>,哪里是<代码> h <代码>打开?将来,考虑使用Python的StaMeTimes <代码> H < /C> >这个代码中与“代码>页眉<代码>相同的对象吗?如果没有,则标题
用于什么?在哪里打开h
?