如何遍历目录和清理文件?

How to loop through directories and clean files?

我正在尝试遍历目录。我的目标是打开目录 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.

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

    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)

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

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