Home > Enterprise >  Why does this Python script to replace text in files break the last file?
Why does this Python script to replace text in files break the last file?

Time:12-01

Source

import os, re

directory = os.listdir('C:/foofolder8')
os.chdir('C:/foofolder8')
for file in directory:
    open_file = open(file,'r')
    read_file = open_file.read()
    regex = re.compile('jersey')
    read_file = regex.sub('york', read_file)
    write_file = open(file, 'w')
    write_file.write(read_file)

The script replaces "jersey" in all the files in C:/foofolder8 with "york". I tried it with three files in the folder and it works. The source notes though that "you may find an error in the last file", which I'm indeed encountering - all text in the last file is simply deleted.

Why does the script break for the last file? The fact that only the last file breaks makes it seem like there's something wrong with the for loop, but I don't see what could be wrong. Calling directory shows there are three files in the directory as well, which is correct.

CodePudding user response:

Try:

import os, re
directory = os.listdir('C:/foofolder8')
os.chdir('C:/foofolder8')
for file in directory:
    with open(file,'r') as open_file:
        read_file = open_file.read()
        regex = re.compile('jersey')
        read_file = regex.sub('york', read_file)
    with open (file, 'w') as write_file:
        write_file.write(read_file)
  • Related