0

I have written the below code to replace the string "YANTRAPRODPATH" with "YantraProd1" in a file and save it:-

fileToModify = open("C:/workspace/PROD/bat1/customer_overrides.properties",'r+')
textToSearch = "<YANTRAPRODPATH>"
textToReplace = "YantraProd1"

f = fileinput.FileInput(fileToModify, inplace=True, backup='.bak')

for line in f:
    print(line.replace(textToSearch, textToReplace))

f.close()

But I am getting below error:-

C:\workspace>python c:/workspace/ReplaceText.py
Traceback (most recent call last):
  File "c:/workspace/ReplaceText.py", line 20, in <module>
    for line in f:
  File "C:\Python27\lib\fileinput.py", line 237, in next
    line = self._readline()
  File "C:\Python27\lib\fileinput.py", line 316, in _readline
    os.rename(self._filename, self._backupfilename)
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

Am I missing something here? And is there a more simpler way to do this?

4
  • The error message does seem to indicate a different line than the ones you posted: os.rename(self._filename, self._backupfilename) Commented Oct 19, 2017 at 15:03
  • @mrCarnivore can you read traceback? Commented Oct 19, 2017 at 15:06
  • @ElmoVanKielmo: I think so. And as it says: the most recent call last. This would mean the most recent call (the one that caused the error) is the one where the author wants to rename a file. Which is not in the printout above. Am I missing something? Commented Oct 19, 2017 at 15:10
  • @mrCarnivore Yes, you are missing something. The traceback says: In line 20 ofc:/workspace/ReplaceText.py f.__iter__() method was called (implicitly by for line in f) and in this method in line 237 of C:\Python27\lib\fileinput.py method self._readline() was called and in this method in line 316 os.rename() function was called and inside this funcion exception of type WindowsError was raised. os.rename() is the most recent call but it was triggered by for line f: via the chain of calls listed in the traceback. Commented Oct 19, 2017 at 15:17

1 Answer 1

1

FileInput constructor expects filename or list of filenames and not file object.

fileToModify = "C:/workspace/PROD/bat1/customer_overrides.properties"
textToSearch = "<YANTRAPRODPATH>"
textToReplace = "YantraProd1"

f = fileinput.FileInput(fileToModify, inplace=True, backup='.bak')

for line in f:
    print(line.replace(textToSearch, textToReplace))

f.close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.