When you use fileinput.input(..., inplace=1)
, the input file is renamed, and any output your code produces on sys.stdout
is written to a newly created file with the original filename.
fileinput
thus has to rename the original file first, by adding .bak
to the name. However, it appears there already is such a file present. Probably you had a bug in your code before and the backup file was never deleted.
Verify that C:/Users/sid/Desktop/app/pom.template.xml.bak
does not contain anything you want to keep, then delete it or move it back to C:/Users/sid/Desktop/app/pom.template.xml
.
If, however, you keep running into this then Python has problems deleting the backup files automatically. On Windows this is usually because another process keeps opening files for their own purposes in the background. You could try deleting the backup file after a timeout:
import time, os
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)
time.sleep(1) # wait 1 second, then delete the backup
os.remove(file + '.bak')
If your files are read-only, make them writable first:
import os, stat
def replaceAll(file,searchExp,replaceExp):
readonly = not os.stat(myFile)[0] & stat.S_IWRITE
if readonly:
os.chmod(file, stat.S_IWRITE)
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
if readonly:
os.chmod(file, stat.S_IREAD)