I'm trying to read lines of some files multiple times in Python.
I'm using this basic way :
with open(name, 'r+') as file:
for line in file:
# Do Something with line
And that's working fine, but if I want to iterate a second time each lines while I'm still with my file open like :
with open(name, 'r+') as file:
for line in file:
# Do Something with line
for line in file:
# Do Something with line, second time
Then it doesn't work and I need to open, then close, then open again my file to make it work.
with open(name, 'r+') as file:
for line in file:
# Do Something with line
with open(name, 'r+') as file:
for line in file:
# Do Something with line
Thanks for answers !
How do we use file.readlines () to read multiple lines using Python? The read function reads the whole file at once. You can use the readlines function to read the file line by line.
How to read multiple text files from folder in Python? - GeeksforGeeks. 1 Import modules. 2 Add path of the folder. 3 Change directory. 4 Get the list of a file from a folder. 5 Iterate through the file list and check whether the extension of the file is in .txt format or not. 6 If text-file exist, read the file using File Handling Functions used:
Using readline () readline () function reads a line of the file and return it in the form of the string. It takes a parameter n, which specifies the maximum number of bytes that will be read. However, does not reads more than one line, even if n exceeds the length of the line.
If the file is small with a few lines, then the task of deleting/eliminating repeated lines from it could be done manually, but when it comes to large files, this is where Python comes to your rescue. Open the input file using using the open () function and pass in the flag -r to open in reading mode.
Use file.seek() to jump to a specific position in a file. However, think about whether it is really necessary to go through the file again. Maybe there is a better option.
with open(name, 'r+') as file:
for line in file:
# Do Something with line
file.seek(0)
for line in file:
# Do Something with line, second time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With