1

Possible Duplicate:
Editing specific line in text file in python

I am writing a software that allows users to write data into a text file. However, I am not sure how to delete the first line of the text file and rewrite the line. I want the user to be able to update the text file's first line by clicking on a button and inputing in something but that requires deleting and writing a new line as the first line which I am not sure how to implement. Any help would be appreciated.

Edit:

So I sought out the first line of the file and tried to write another line but that doesn't delete the previous line.

file.seek(0)
file.write("This is the new first line \n")
Community
  • 1
  • 1
user1111042
  • 1,461
  • 4
  • 18
  • 23

2 Answers2

3

You did not describe how you opened the file to begin with. If you used file = open(somename, "a") that file will not be truncated but new data is written at the end (even after a seek on most if not all modern systems). You would have to open the file with "r+")

But your example assumes that the line you write is exactly the same length as what the user typed. There is no line organisation in the files, just bytes, some of which indicate line ending. Wat you need to do is use a temporary file or a temporary buffer in memory for all the lines and then write the lines out with the first replaced.

If things fit in memory (which I assume since few users are going to type so much it does not fit), you should be able to do:

lines = open(somename, 'r').readlines()
lines[0] = "This is the new first line \n"
file = open(somename, 'w')
for line in lines:
    file.write(line)
file.close()
Anthon
  • 69,918
  • 32
  • 186
  • 246
1

You could use readlines to get an array of lines and then use del on the first index of the array. This might help. http://www.daniweb.com/software-development/python/threads/68765/how-to-remove-a-number-of-lines-from-a-text-file-

Pete
  • 582
  • 5
  • 8