ValueError:关闭文件的I / O操作

时间:2014-03-25 14:36:23

标签: python

好的,我必须将file.txt分成更多文件,这里是代码

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()

所以,如果我运行它会给我这个错误:

todoController\WordlistSplitter.py", line 9, in <module>
    f.writelines(line)
ValueError: I/O operation on closed file

我明白如果你做一个for循环,文件会被关闭,所以我试图把f放在for循环中,但它不起作用而不是得到:

out1.txt
 1
 2
 3
 4

out2.txt
 5
 6
 7
 8

我只得到文件的最后一行。我该怎么办,有什么方法可以回忆起我之前定义的开放功能吗?我是一个非常新的python,所以我很抱歉,如果我问的是我不能做的事情,请耐心等待:D

4 个答案:

答案 0 :(得分:0)

你关闭了文件但没有从for循环中断。

答案 1 :(得分:0)

如果a == d你正在关闭f然后稍后(在下一次迭代中)你试图写入它导致错误。
还 - 你为什么两次关闭?

答案 2 :(得分:0)

您应该删除第一个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()

答案 3 :(得分:0)

f.close()循环中的for,然后open新文件f,因此下一次迭代时出错。您还应该使用with来处理文件,从而节省您需要明确close个文件。

由于您希望一次向每个out文件写入四行,您可以按如下方式执行此操作:

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)

请注意,我使用变量名称使其更清晰。

相关问题