How do i go back to the top of a text file in python?
I am new to python and I am learning some basic file reading stuff. I am trying to read a file and count the number of new lines and also print lines that start with 'From: ' . Show This is the code I have for that:
I know that I can do this in one loop but I am trying to learn something here. As soon as the first loop is executed, 'line' is at the end of the file. So when it runs the second loop, it does not print anything. I tried putting in line = 0, it doesnt work. How to I got back to start of file? Thank you for your help. asked Oct 12, 2016 at 17:21
seek() takes an argument that goes back to that "byte" so 0 byte will go back to the start of the file.
answered Oct 12, 2016 at 17:23
1 Try this out :
To get back to start of file use answered Oct 12, 2016 at 17:23
MMFMMF 5,5423 gold badges15 silver badges19 bronze badges
1 minute read This is something I used to stumble on a lot in the early days of my Python coding adventure so I thought to write a quick article about it. Python Open fileOpening a file for read or write in Python can be achieved with the following code:
Python Read fileTo read content of the file we simply use the read() method
Note that Python will print the newline character and will not split lines for you (but that’s material for another day/post) Where is my text?Say you want to print again file content issue the same command again will leave you with something like this
Not a lot to see on screen, so where did our file’s content go? Python seek()When python reads a file’s content it will move file current position to the end of the file so trying to re-read it again will yield the above result. Nothing as there is nothing else to read. You can easily go back to the beginning of the file with the seek() method which is used like this:
Now if you try to read the file again all content will be correctly displayed
How do I go back to the top of a file in Python?We can move the file pointer to the beginning of the file using the seek() method by passing the setting whence to 0. The 0 indicates the first byte, which is the beginning of the file.
How do you get to the beginning of a text file in Python?seek() takes an argument that goes back to that "byte" so 0 byte will go back to the start of the file. of note... If your are both reading and writing (mode r+ ), an easy way to go back to the end of the file (presumably to append to it) is to call seek(-1) .
How do I go back to a step in Python?Your "go back a step" operation is what's commonly referred to as a GoTo, probably the most hated operation in any programming language. It is not supported in Python, you must use other methods like loops. You go back by using loops, like those while loops you have.
How do you write to top of file in Python?To prepend content to a file in Python, open the file in read+write mode, seek to the start of the file, then write the newline plus the original file content.
|