1

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 ?

myosis
  • 45
  • 9
  • This would be really obvious if you printed out what `stringNub` is. :) Try `print(repr(stringNub))`. – Mateen Ulhaq Mar 21 '20 at 11:43
  • 1
    Does this answer your question? [How to read a file without newlines?](https://stackoverflow.com/questions/12330522/how-to-read-a-file-without-newlines) – Mateen Ulhaq Mar 21 '20 at 11:43

2 Answers2

1

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')
Damzaky
  • 6,073
  • 2
  • 11
  • 16
1

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: ","")
kederrac
  • 16,819
  • 6
  • 32
  • 55