Save-to-file code not quite working completely

MRAB python at mrabarnett.plus.com
Sat Aug 8 18:02:26 EDT 2020


On 2020-08-08 21:51, Steve wrote:
> 
> I have a file containing specifications. My .py program can read and
> manipulate the data but I cannot seem to get it to update the original file
> properly.
> 
> The code is simple and works except that the original line remains in the
> file after the new updated one has been added.
> 
> My code:
> =======================================================
> 
> import fileinput
> import sys
> 
> def ReplaceLine(file,searchExp,replaceExp):
>      for line in fileinput.input(file, inplace=1):
>         # if searchExp in line:
>          line = line.replace(searchExp,replaceExp) #.rstrip()
>          sys.stdout.write(line)
>          
> NewLine = "MSN Monitor Serial Number:  111111111-T4464                   ##
> \n "
> ReplaceLine("Specifications.txt","MSN", NewLine)
> print()
> PauseHere = input("Paused")
>   =====================================
> The text file:
> 1 MSN Monitor Serial Number:  111111111-T4464     ##
>    Monitor Serial Number:  88888888-T4464                  ##
> 2 TLN TestStrip Lot Number:   45001 82624                  ##
> 3 SED Strip Expire Date:      2021-02-28                          ##
> 4 SEC Sensor Sequence Code:   68                                   ##
> 5 SCN Sensor Code Number:     F95                                  ##
> 6 SEN Sensor Serial Number:   0M000APJYWM             ##
> 7 SDE Sensor Date to Expire:  2020-12-31                       ##
> 8 SDN Sensor Day Number:      1                                       ##
> 9 DTD Data Time Date          Fri Aug 07, 2020 21:30       ##
> =====================================
> That second line shown was the original line for MSN. The replacement line
> should have replaced the original line not just get added to the file.  It
> should have been replaced. What is in line 2, should have "1 MSN" at the
> beginning but that somehow disappeared.
> 
> So close, so simple...
> How do I fix this?
> Steve
> 
> P.S. I read to add ".rstrip()" but that messed things even more...  (-:
> 
In the .replace line you're asking it to replace any occurrence of "MSN" 
in the line with a new string.

It's doing that.

I'll add <<...>> around the replacement to make its position clearer:

 >>> line = " 1 MSN Monitor Serial Number:  111111111-T4464     ##\n"
 >>> line.replace("MSN", "<<MSN Monitor Serial Number:  111111111-T4464 
                  ##\n >>")
' 1 <<MSN Monitor Serial Number:  111111111-T4464                   ##\n 
 >> Monitor Serial Number:  111111111-T4464     ##'


More information about the Python-list mailing list