pythonvalueerror

How to loop through directories and clean files?


"Hi, I'm trying to loop through directories to modify some files. Specifically, I want to open the directory 'ff' to make changes to the files inside.

I tried using open(ff, 'r'), but it didn't work as expected.

Also, the files (e.g., d.txt) contain numbers and symbols like 'x', '1', and quotes on every line. I'm looking for a way to remove these characters from each line. Could you help me figure this out?"

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

  • 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.