Search code examples
python-2.7overwrite

Python: Will not Write 'w'


Python 2.7 won't overwrite existing files. It will only create new ones.

Every file that already exists named push.lua does not write changes.

# Push Replacer .py

import os

file_open = open('push_new.lua', 'r')
file_contents = file_open.read()

for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    for file in files:
        if (file == 'push.lua'):
            with open(file, 'w') as f:
                f.write(file_contents)
                f.close()
            
file_open.close()

Solution

  • Your code always opens and overwrites push.lua in the current working directory, not in any subdirectory that it might a file with that name in it. You need to do open(os.path.join(root, file), 'w') instead of just open(file, 'w').

    I suspect you were trying to head in this direction with your path variable, but you never actually use the path variable for anything.