Appending line to a existing file having extra new line in Python
python
Solution
You can't, because, well, append mode does exactly that: It appends. To the newline. You will have to read in the file, remove the newline at the end, write it out and then append.
Or, open the file for reading and writing (mode `'r+'`), seek to the end, remove the newline, and then continue with writing.
I think this could do the trick:
f = open('file.txt', 'r+')
f.seek(-2, 2) # last character in file
if f.read(2) == '\n\n':
f.seek(-1, 1) # wow, we really did find a newline! rewind again!
f.write('orange')
f.close()
Problem
I have a text file ``` apple banana ``` Now you watch closely there is blank line at the end. When in do append ``` f = open("file.txt",'a') f.write("orange") f.close() ``` I get output: ``` apple banana orange ``` I want to remove the blank line in between during appends. I know i can do that manually going to the file and removing the extra new line. But i want to do it in python. So every time the blank line is there its gets removed automatically like this: ``` apple banana orange ``` I search and experimented but no avail