"ValueError:对关闭文件的I/O操作"在循环写入文件时 [英] "ValueError: I/O operation on closed file" while writing to a file in a loop
问题描述
我必须将file.txt分成更多文件.这是代码:
I have to divide a file.txt into more files. Here's the code:
a = 0
b = open("sorgente.txt", "r")
c = 5
d = 16 // c
e = 1
f = open("out"+str(e)+".txt", "w")
for line in b:
a += 1
f.writelines(line)
if a == d:
e += 1
a = 0
f.close()
f.close()
所以,如果我运行它,它将给我这个错误:
So , if i run it it gives me this error :
todoController\WordlistSplitter.py", line 9, in <module>
f.writelines(line)
ValueError: I/O operation on closed file
我了解到,如果执行for循环,文件将关闭,因此我尝试将f放入for循环中,但由于没有得到,所以它不起作用:
I understood that if you do a for loop the file gets closed so I tried to put the f in the for loop but it doesn't work because instead of getting:
out1.txt
1
2
3
4
out2.txt
5
6
7
8
我只得到文件的最后一行.我应该怎么办?有什么方法可以让我回忆起之前定义的打开函数?
I get only the last line of the file. What should I do? Are there any way I can recall the open function I defined earlier?
推荐答案
您在 for
循环内 f.close()
,然后不要 open
作为 f
的新文件,因此在下一次迭代时出错.您还应该使用 with
来处理文件,这样就无需显式地 close
来处理文件.
You f.close()
inside the for
loop, then do not open
a new file as f
, hence the error on the next iteration. You should also use with
to handle files, which saves you needing to explicitly close
them.
由于您希望一次向每个 out
文件写入四行,因此可以执行以下操作:
As you want to write four lines at a time to each out
file, you can do this as follows:
file_num = 0
with open("sorgente.txt") as in_file:
for line_num, line in enumerate(in_file):
if not line_num % 4:
file_num += 1
with open("out{0}.txt".format(file_num), "a") as out_file:
out_file.writelines(line)
请注意,我已经使用变量名使事情更清楚了.
Note that I have used variable names to make it a bit clearer what is happening.
这篇关于"ValueError:对关闭文件的I/O操作"在循环写入文件时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!