pythonos.walk

loop and change the first letter of file


i have about 300 files in a folder in which the first line is 1, i would like to change it to 0,

this is the piece of code i'm using to get it done

import os


for root,dirs,files in os.walk('/home/decentmakeover2/try/'):
for file in files:

    if file.endswith('.txt'):
        with open(file, 'r+b') as f:
            line = next(f) # grab first line
            old = '1'
            new = '0' 
            f.seek(0) 
            f.write(line.replace(old, new))

but i get this error

Traceback (most recent call last):
  File "one.py", line 8, in <module>
with open(file, 'r+b') as f:
IOError: [Errno 2] No such file or directory: 'yield_021.txt'

but the thing is the file is present in the folder and its just like the other files,if i delete the file then i get the same error but with a different filename

any ideas?


Solution

  • Use os.path.join, and join your root with your filename, since open needs the fully qualified path to work.

    with open(os.path.join(root, file), ...) as f:
    

    Where root is the first value returned by os.walk.