'How to loop through directories and clean files?

I am trying to loop through directories. My goal is to open the directory ff for modifications in the files.

When I try open (ff, 'r') it does not work.

Further, the files in the directories d.txt has numbers and symbols x, 1, " in every line. I am seeking to remove these characters from each line.

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

The Error that I am getting:

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


Solution 1:[1]

First of all, I think this part is wrong in your code:

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

As this will assign the last filename to ff. So I have moved the following code under this for loop. Now it will run for all files.

I belive this code should work:

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: if the open('ff','r') line doesn't work then maybe the path you are giving is wrong. What are the contents of filenames? And why are you adding d.txt at the end?? Please edit your post and add these details.

Solution 2:[2]

Move f.close() to outside of loop. You're closing the file everytime loop runs.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sabito 錆兎 stands with Ukraine
Solution 2 Cagri