Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read multiple times lines of the same file Python [duplicate]

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 !

like image 763
Retsim Avatar asked Oct 10 '14 08:10

Retsim


People also ask

How do we use readlines () to read multiple lines using Python?

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?

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:

How do you read multiple lines of data from a file?

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.

How do I delete repeated lines from a file in Python?

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.


1 Answers

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
like image 168
Tim Zimmermann Avatar answered Sep 23 '22 00:09

Tim Zimmermann