Search code examples
pythonfilereadlines

Reading multiple opened files using readlines() results in empty array


I have 2 files that I want to manipulate. One of the files (in.txt) is opened in read mode, 'r', the other (out.txt) is in append mode and should be able to be read from as well, 'a+'.

As an example let's suppose the contents of the in.txt file is:

Foo

And the contents of the out.txt file is:

Bar

If I run this script on the same folder the files are stored at, (please, pay no attention to variable names, this is just to simplify the example...I hope):

with open('in.txt', 'r') as i, open('out.txt', 'a+') as o:
    in_data = i.readlines()
    out_data = o.readlines()
    
    print(in_data)
    print(out_data)

This is the output:

['Foo\n']
[]

The contents of the output file will not be read into the array.

How should I proceed to be able to use both files as expected? Is this related to the file pointer of the open operation?


Solution

  • This has nothing to do with opening multiple files.

    When you open a file in append mode, you're initially positioned at the end of the file, so there's nothing to read. You need to seek to the beginning to read the contents.

    with open('in.txt', 'r') as i, open('out.txt', 'a+') as o:
        in_data = i.readlines()
        o.seek(0)
        out_data = o.readlines()
        
        print(in_data)
        print(out_data)