问题
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
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?
回答1:
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.
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.
回答2:
You close the file but you don't break from for loop.
回答3:
if a == d you are closing f and then later (in the next iteration) you are trying to write to it which causes the error.
also - why are you closing f twice?
回答4:
You should probably remove the first f.close()
:
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()
来源:https://stackoverflow.com/questions/22637758/valueerror-i-o-operation-on-closed-file-while-writing-to-a-file-in-a-loop