I suspect that the file already ends in a newline character (or \r\n since you’re on Windows), so you’re appending after that. It can difficult to see this by viewing the file unless you have an editor that will show you special characters.
If you read the original file and print the result, does the output have a blank line? That would be a sign that there’s a newline at the end (and then print is adding another one, causing a blank line in the output)
It can be tricky to remove because some text editors will add a newline when you save, but it’s possible to do it that way. Or if you created the file in Python, you can make sure that you don’t end on a newline.
@Eyalvr12 -
If I may make a suggestion - when opening files it’s generally better to get into the habit of using a context manager:
with open(path, "r") as f:
s = f.read()
s = s.rstrip('\n') # strips all new lines at the end of the text
# s.rstrip() would strip all whitespace, which is perhaps what you want
s = f"{s} = {result}\n"
with open(path, "w+") as f:
f.write(s)
now, what changes the value of line is when I do the += ‘=’ + str(result).
And yes ,I read the line from the original file
Is there anyway to go around that?
If file have only one row 46 + 19 (or you want to add to the last row) then this should work: open file, go to end, go one character before end, write:
with open("my_file.txt", "a") as f:
f.seek(0, 2)
f.seek(f.tell() - 1)
f.write(" = 65")
# 46 + 19 = 65
I was trying to about about the whitespace at the end of line, but maybe this is the wrong way to do that.
>>> print(line) # is it this?
46 + 19
>>> print(line) # or this
46 + 19
>>> # ^ note the blank line before the prompt
A simpler way to check is to print len(line) and/or line.endswith("\n"). If the length is 8, there’s an extra character in there that you don’t see (whitespace at the end).
That won’t work (at least not on all OS’s - for instance it doesn’t work on Darwin). If you open the file in ‘a’ mode it may still append at the end and not overwrite, despite the seek position. One way to make this work is the code I posted earlier. Another way is Aivar’s code if you replace ‘a’ by ‘r+’.
To check the original file (and the modified file), you could use an editor that makes white-space and control chars visible, or do something like: