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.
write_file? That is, putwrite_file.close()afterwrite_file.write(read_file)open_filewhile you're at it. It's best to handle this using awithcontext, likewith open(file, 'r') as open_file:os.chdir('C:/foofolder8')is unnecessary and does nothing in the context of your script. For optimal performance, you should compile your regex outside the loop since it doesn't change, and you can reuse the same. Regex compilation is a heavy operation.