I tried to update certain text file with new string in a new row at the end of the file with Python. The file itself can have empty line at the end and sometime not. I tried the following script to do this.
with open(fname, 'a') as file:
file.write("\n" newRow)
newRow is a variable containing new text that will be added. It works fine if the last row of the file is not empty. However, this is not correct in the last row of the file is an empty space. In this case, the file will have an empty space between the last row and newRow.
aaaa
bbbb
newRow
I guest the question is how can i check whether the last row of the file is empty line. I found that using readlines() can store each row of the text file into a list, then i can check the last row. But i don't know how to do this if i use 'with open'. So at the end, the intended result is as follow for any text files
aaaa
bbbb
newRow
How can i reach this result?
thank you in advance
CodePudding user response:
Try this:
with open("prova.txt", "r ") as file:
lines = file.readlines()
# this will put the seek pointer to the end of file
file.seek(0,2)
if lines[len(lines) - 1] == '\n':
file.write("newRow")
else:
file.write("\nnewRow")