我对Python很陌生,但根据我在互联网上收集的内容,ValueError: I/O operation on closed file
基于未正确关闭写入文件。
我已经尝试重新定位close语句以与每个循环对齐而没有任何成功。
我还试图重新定位我最初打开文件进行写入的地方,但没有成功。我确信我错过了一个明显的错误。非常感谢您帮助识别这个错误。
import os # Loop through files/folders
import xlrd # Used to read Excel
import time # Set sleep timers
directory = 'C:/Path/to/file/'
for subdir, dirs, files in
os.walk(directory):
# Loop through directory
files = [file for file in files if file.endswith('.xls')]
out_14 = open(str("C:/path/to/file/14.out"), "w")
out_15 = open(str("C:/path/to/file/15.out"), "w")
for file in files: # Loop through files in directory
wb_path = os.path.join(subdir, file)
wb = xlrd.open_workbook(wb_path)
ws = wb.sheet_names()
for worksheet in ws: # Loop through worksheets
sheet = wb.sheet_by_name(worksheet)
num_rows = sheet.nrows - 1
num_cells = sheet.ncols - 1
curr_row = -1
while curr_row < num_rows: # Loop through all rows
temp_14 = []
temp_15 = []
curr_row += 1
curr_cell = -1
while curr_cell < num_cells: # Loop through all cells within current row
curr_cell += 1
# Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
cell_type = sheet.cell_type(curr_row, curr_cell)
cell_value = sheet.cell_value(curr_row, curr_cell)
if cell_type == 3: # Fix Dates yyyy/mm/dd
year, month, day, hour, minute, second = xlrd.xldate_as_tuple(cell_value, 0)
cell_value = (str(year) + "/" + str(month) + "/" + str(day))
elif cell_type == 2: # Round numeric values
cell_value = round(cell_value, 3)
temp_15.append(cell_value)
out = str('~'.join('"{0}"'.format(item) for item in temp_15)) # Tilde delimited while encapsulated with quotes
out_15.write(out)
# time.sleep(1.0)
out_15.close()
答案 0 :(得分:1)
在关闭文件后尝试写入文件时,实际上会引发错误。它在循环的第一次迭代结束时关闭。在第二次迭代中,您将收到错误。
您正在使用模式&#39; w&#39;打开out_15文件,因此每次打开它时都会覆盖它。然后我们可以假设您想要在循环for file in files
之外打开和关闭它。
那么为什么不使用更现代的with
语句,并将for
循环包含在内:
with open(str("C:/path/to/file/15.out"), "w") as out_15:
for file in files:
(...)
这样您就不必费心关闭文件,它会在with
块结束时自动生成。
请参阅此问题:Valueerror : I/O operation on closed file
其他说明: - 你打开了out_14,但是你从不使用它,也从不关闭它。 - 而不是str(&#34; C:/...")你可以使用r&#34; c:......&#34; :r&#34;&#34;是一个&#34; raw&#34;字符串,它不会将反斜杠解释为转义字符。实际上str()在你的情况下是不必要的。