python:模块:打开(os.path.join())

时间:2020-07-15 13:51:33

标签: python valueerror

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

2 个答案:

答案 0 :(得分: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?请编辑您的信息并添加这些详细信息。

答案 1 :(得分:1)

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