Я довольно новичок в Python, но, основываясь на том, что я собрал в Интернете, кажется, что ValueError: I/O operation on closed file
основан на неправильном закрытии файла для записи.Python - ValueError: операция ввода/вывода в закрытом файле
Я попытался переставить оператор закрытия, чтобы выстроить линию с каждым циклом без каких-либо успехов.
Я также попытался изменить положение, где я изначально открывал файлы для записи без каких-либо успехов. Я уверен, что есть явная ошибка, которую мне не хватает. Ваша помощь в определении этой ошибки будет принята с благодарностью.
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()
Вы закрываете 'out_15' в цикле, а не затем –
@PeterWood: почему вы не ответили? –
@ EricLevieil У меня нет времени, и кто-то другой мог бы ответить лучше. –