Python:解析一个目录的txt文件,将包含字符串的行保存到新目录,ValueError:对关闭的fi执行I/O操作

2024-07-03 08:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

import os
import sys

a = os.listdir("C:\\Python27\\forms2")

i = 0

big_file = open("c:\\Python27\\forms2\\%s" %a[i], 'r')
small_file3 = open("c:\\Python27\\forms3\\%s" %a[i], 'w')
linez = big_file.read()
for line in linez:
   if 'TextControl' in linez:
      small_file3.write(line)

   if 'http://' in linez:
      small_file3.write(line)
   i = i + 1
   big_file.close()
   small_file3.close()

输出为

Traceback (most recent call last):
  File "C:\Python27\testreadwrite", line 13, in <module>
    small_file3.write(line)
ValueError: I/O operation on closed file

“testreadwrite”是脚本的名称。为什么要在应该注入“a”列表变量的地方注入?你知道吗


Tags: inimportcloseifoslineopenfile
3条回答

您正在for循环结束时关闭文件

for line in linez:
   ...
   big_file.close()
   small_file3.close()

您应该在for循环之后关闭文件

for line in linez:
   ...
big_file.close()
small_file3.close()

您可以使用context manager来避免将来出现此类问题:

with open("c:\\Python27\\forms2\\%s" %a[i], 'r') as big_file, \
     open("c:\\Python27\\forms3\\%s" %a[i], 'w') as small_file3:
    linez = big_file.read()
    for line in linez:
       ...

所以你不必自己打电话给close。你知道吗

您正在对循环中的文件描述符调用close(),循环中的文件描述符为零 理智。您可能希望在循环之外/之后关闭文件描述符。你知道吗

错误消息:

   I/O operation on closed file

告诉您问题所在,您正在尝试对关闭的文件执行IO操作,在本例中,写入关闭的文件。你知道吗

问题是,您正在关闭循环中的输出文件("small_file3",您可能希望在前面提到的循环之后关闭它。你知道吗

您可以在for循环之前关闭输入("big_file")文件,然后在for循环之后关闭输出文件。你知道吗

还可以考虑使用^{}构建打开文件的路径。你知道吗

相关问题 更多 >