Skip to content Skip to sidebar Skip to footer

Deleting The First Line Of A Text File In Python

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 t

Solution 1:

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 inlines:
    file.write(line)
file.close()

Solution 2:

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-

Post a Comment for "Deleting The First Line Of A Text File In Python"