I am currently programming a game that requires reading and writing lines in a text file. I was wondering if there is a way to read a specific line in the text file (i.e. the first line in the text file). Also, is there a way to write a line in a specific location (i.e. change the first line in the file, write a couple of other lines and then change the first line again)? I know that we can read lines sequentially by calling:
f.readline()
Edit: Based on responses, apparently there is no way to read specific lines if they are different lengths. I am only working on a small part of a large group project and to change the way I’m storing data would mean a lot of work.
But is there a method to change specifically the first line of the file? I know calling:
f.write('text')
Writes something into the file, but it writes the line at the end of the file instead of the beginning. Is there a way for me to specifically rewrite the text at the beginning?
If all your lines are guaranteed to be the same length, then you can use
f.seek(N)to position the file pointer at the N’th byte (where N is LINESIZE*line_number) and thenf.read(LINESIZE). Otherwise, I’m not aware of any way to do it in an ordinary ASCII file (which I think is what you’re asking about).Of course, you could store some sort of record information in the header of the file and read that first to let you know where to seek to in your file — but at that point you’re better off using some external library that has already done all that work for you.
Unless your text file is really big, you can always store each line in a list:
(note I’ve stripped off the newline so you don’t have to remember to keep it around)
Then you can manipulate the list by adding entries, removing entries, changing entries, etc.
At the end of the day, you can write the list back to your text file:
Here’s a little test which works for me on OS-X to replace only the first line.
test.dat
test.py