myosis
myosis

Reputation: 45

Unwanted '\n' removed when writing to txt line

So I have this text file:

Hoi

Total: 5700
-
-

And this code to change the Total: value:

with open("TEST.txt") as f:
    lines = f.readlines()
string = (lines[2])
stringNub = string.replace("Total: ","")

num = 300
sum = int(stringNub) + int(num)

with open('TEST.txt','r') as file:
    filedata = file.read()
    filedata = filedata.replace(stringNub, str(sum))
with open('TEST.txt','w') as file:
    file.write(filedata)

This works but the result is minus one Enter '\n'.

Hoi

Total: 6000-
-

How do I keep it from removing this enter ?

Upvotes: 1

Views: 64

Answers (2)

kederrac
kederrac

Reputation: 17322

at this line filedata = filedata.replace(stringNub, str(sum)) your variable stringNub containes the full line with the \n at the end, by replacing with str(sum) you are also removing the \n, to fix you could do :

with open('TEST.txt','r') as file:
    filedata = file.read()
    filedata = filedata.replace(stringNub, str(sum) + '\n')

or you could difine stringNub without \n using str.strip and keep the rest of your code without changes:

stringNub = string.strip().replace("Total: ","")

Upvotes: 1

Damzaky
Damzaky

Reputation: 10826

It's because when you convert stringNub into an int, the \n gets removed, the solution is simply add \n again when you want to write. Change the following line:

filedata = filedata.replace(stringNub, str(sum))

to this:

filedata = filedata.replace(stringNub, str(sum) + '\n')

Upvotes: 1

Related Questions