【问题标题】:How to loop through directories and clean files?循环遍历目录并清理文件
【发布时间】:2020-11-05 01:08:52
【问题描述】:

我正在尝试遍历目录。目标是打开目录ff 并在文件中进行修改。为什么open (ff, 'r') 不起作用?

文件d.txt 的每一行都有数字和符号x1"。我想从每一行中删除这些字符。

import os

filenames= os.listdir (".")
for filename in filenames:
    ff = os.path.join(r'C:\Users\V\Documents\f\e\e\data', filename, 'd.txt')

f = open(str(ff),'r')  #this line does not open the file
a = ['x','1','"']
lst = []
for line in f:
    for word in a:
        if word in line:
            line = line.replace(word,'')
            lst.append(line)
        f.close()

我得到的错误:

for line in f:
    ValueError: I/O operation on closed file.

【问题讨论】:

  • folders 是什么?
  • 我们看到的代码中没有产生该异常。这里没有 I/O 操作。
  • 我相信您正在执行文件打开范围之外的写操作,因此 I/O 错误。
  • 不使用\你需要你使用\\
  • 那么您在for word in a 的第一次迭代中使用f.close() 关闭文件,因此如果文件中有多个单词,它将尝试在下一次迭代中写入已关闭的文件.您必须将该行移出循环。

标签: python valueerror


【解决方案1】:

首先,我认为这部分在你的代码中是错误的:

    for filename in filenames:
        ff = os.path.join(r'C:\Users\V\Documents\f\e\e\data', filename, 'd.txt')

因为这会将最后一个文件名分配给ff。所以我在这个for循环下移动了以下代码。现在它将针对所有文件运行。

我相信这段代码应该可以工作:

import os 

filenames = os.listdir('.')

lst = []
a = ['x','1','"']

for filename in filenames:
    ff = os.path.join(r'C:\Users\V\Documents\f\e\e\data', filename, 'd.txt')
    
    with open(ff,'r') as file:
        for line in file:
            for word in a:
                if word in line:
                    line = line.replace(word,'')
                    lst.append(line)
                    
    with open(ff,'w') as file:
        for line in lst:
            file.write(line)

编辑:如果open('ff','r') 行不起作用,那么您给出的路径可能是错误的。 filenames的内容是什么?你为什么要在最后添加d.txt?请编辑您的帖子并添加这些详细信息。

【讨论】:

  • 是的,这段代码有效,它循环遍历目录,但不知何故,'"' quatation 标记没有被删除。
  • 文件需要关闭。没有他们就被毁了。最后一个文件中的行被保存在不同文件夹的文件中。但 open(ff) 有效。所以也许这是一个不同的问题
【解决方案2】:

f.close() 移到循环外。每次循环运行时都会关闭文件。

import os

filenames= os.listdir (".")
for filename in filenames:
    ff = os.path.join(r'C:\Users\V\Documents\f\e\e\data', filename, 'd.txt')

f = open(str(ff),'r')  #this line does not open the file
a = ['x','1','"']
lst = []
for line in f:
    for word in a:
        if word in line:
            line = line.replace(word,'')
            lst.append(line)

f.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多