Here is my code for replacing all the occurrences of kyle and john with mike and jim respectively.
import os
import fileinput
import sys
rootdir ='C:/Users/sid/Desktop/app'
searchTerms={"kyle":"mike","john":"jim"}
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
for subdir, dirs, files in os.walk(rootdir):
for file in files:
path=subdir+'/'+file
for key,value in searchTerms.items():
replaceAll(path,key,value)
This was working fine for a test directory i created. When i changed the rootdir to my actual java project directory, I was getting
Traceback (most recent call last):
File "C:\Users\sid\Desktop\test_iterator.py", line 19, in <module>
replaceAll(path,key,value)
File "C:\Users\sid\Desktop\test_iterator.py", line 10, in replaceAll
for line in fileinput.input(file, inplace=1):
File "C:\Python33\lib\fileinput.py", line 261, in __next__
line = self.readline()
File "C:\Python33\lib\fileinput.py", line 330, in readline
os.rename(self._filename, self._backupfilename)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:/Users/sid/Desktop/app/pom.template.xml.bak'
Can someone please explain why im getting this error. I have read the post about os.rename() FileExistsError but i couldnot understand it. Can some please explain in detail.