DavidU DavidU - 3 months ago 11
Python Question

Iterate through all files in a directory and find and replace text - Python

Baby brand new. This was Frankenstein'ed together from a few similar topics, none of which seemed to cover the necessary step of nesting a find and replace inside a file loop.

I am attempting to iterate through every file in a folder (not recursively, I only have one folder level) of a specific type (listed here as a '.LIC') and replace a short bit of text. The following is as close as I could come:

import glob, os, fileinput
from glob import glob
root_dir = r"myPath"
os.chdir(root_dir)
for file in glob, glob('*.LIC'):
filename = str(file)
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace('findText', 'replaceText'), end='')


As you can imagine this went swimmingly. The error code is placed below.

OSError Traceback (most recent call last)
<ipython-input-61-e2fd0e9a5df9> in <module>()
6 filename = str(file)
7 with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
----> 8 for line in file:
9 print(line.replace('findText', 'replaceText'), end='')
10

C:\Users\Me\Anaconda3\lib\fileinput.py in __next__(self)
246 def __next__(self):
247 while True:
--> 248 line = self._readline()
249 if line:
250 self._filelineno += 1

C:\Users\Me\Anaconda3\lib\fileinput.py in _readline(self)
333 pass
334 # The next few lines may raise OSError
--> 335 os.rename(self._filename, self._backupfilename)
336 self._file = open(self._backupfilename, self._mode)
337 try:

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<function glob at 0x00000000013D3400>' -> '<function glob at 0x00000000013D3400>.bak'


I think my problem is nesting a reference to 'file', but I am unsure how to resolve this.

Thank you for the help in advance.

Answer

You should loop over the result of glob and not a tuple with the function object glob:

for filename in glob('*.LIC'):
    with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace('findText', 'replaceText'),  end='')