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.

Allure
  • 261
  • 1
  • 9
  • 3
    Did you try to close `write_file`? That is, put `write_file.close()` after `write_file.write(read_file)` – Abdelhakim AKODADI Dec 01 '21 at 04: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:` – rchome Dec 01 '21 at 05: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. – Abdelhakim AKODADI Dec 01 '21 at 05:04
  • @AbdelhakimAKODADI would suggest writing that as an answer! – Allure Dec 01 '21 at 05:41
  • Compiling the same regex again and again inside the loop completely removes any benefits from separately compiling it. – tripleee Dec 01 '21 at 06:55

1 Answers1

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)
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61