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:

TCPServeraddress      april.com
NODename              hostname
COMMmethod            TCPip
NFSTIMEout            0
TCPBuffsize           32
TXNB                  25600
TCPWINDOWSIZE         64
TCPNODELAY            YES
LARGECOMMBUFFERS      YES
MANAGEDServices     Schedule
SCHEDMODe             prompted
PASSWORDAccess        generate
ERRORLOGRetention     2 d
ERRORLOGName          /ngs/hostname/logs/dsmerror.log
SCHEDLOGRetention     2 d
SCHEDLOGName          /ngs/hostname/logs/dsmsched.log

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

import fileinput


textToSearch = "hostname" 
print ("Please type in the TSM Hostname:")
textToReplace = raw_input( "Hostname/Nodename: " )

print ("***Updating dsm.sys file****")
fileToSearch  = "/Users/bob/Desktop/FinalizedPythonScripts/helloworld"

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()

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:

TCPServeraddress      april.com
NODename              test
COMMmethod            TCPip
NFSTIMEout            0
TCPBuffsize           32
TXNB                  25600
TCPWINDOWSIZE         64
TCPNODELAY            YES
LARGECOMMBUFFERS      YES
MANAGEDServices     Schedule
SCHEDMODe             prompted
PASSWORDAccess        generate
ERRORLOGRetention     2 d
ERRORLOGName          /ngs/test/logs/dsmerror.log
SCHEDLOGRetention     2 d
SCHEDLOGName          /ngs/test/logs/dsmsched.log
smsched.log

Advertisement

Answer

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

Here’s the script:

import fileinput

textToSearch = "hostname" 
print ("Please type in the TSM Hostname:")
textToReplace = raw_input( "Hostname/Nodename: " )
print ("***Updating dsm.sys file****")
fileToSearch  = "/Users/bob/Desktop/FinalizedPythonScripts/helloworld"
for line in fileinput.input(fileToSearch, inplace=True):
    print line.replace(textToSearch, textToReplace),
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement