Skip to content
Advertisement

Python Using Fileinput to Replace Words

I am using Python 2.7 with MAC OS X and wrote a program to replace a word in a file with another word. Any time that word shows up in that file I want it replaced with another word that the user specifies. It seems to be working but it seems to be outputting a couple extra lines on the bottom that are copied from the file. Does anyone know why it is doing this?

Original file:

JavaScript

After running my script, the user will input “test” as hostname:

JavaScript

I get the modified file correctly but has the extra “smsched.log” as the last line which does not exist in the original file, I have repeated this process and it happens everytime:

JavaScript

Advertisement

Answer

Use the fileinput.input(filePath, inplace=True) method instead of the open(..) method

Here’s the script:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement