0

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.

5
  • 3
    Did you try to close write_file? That is, put write_file.close() after write_file.write(read_file) Commented Dec 1, 2021 at 4:59
  • 1
    You should also close open_file while you're at it. It's best to handle this using a with context, like with open(file, 'r') as open_file: Commented Dec 1, 2021 at 5:01
  • Also, 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. Commented Dec 1, 2021 at 5:04
  • @AbdelhakimAKODADI would suggest writing that as an answer! Commented Dec 1, 2021 at 5:41
  • Compiling the same regex again and again inside the loop completely removes any benefits from separately compiling it. Commented Dec 1, 2021 at 6:55

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

5 Comments

You missed the most important part, which is closing write_file
@AbdelhakimAKODADI : It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.
I agree, but that's not my point. Your with ... will only close open_file. You forgot to close write_file
@AbdelhakimAKODADI : ohh.. modified accordingly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.