Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: open two files as one fileobject

Tags:

python

I have two files: a header and the body. I am using a library to read the whole thing. I can use "fileinput.input" to create one FileInput object and hand this to the library that reads the data. Problem is FileInput objects do not have a '.read' attribute which the library seems to expect.

I need a FileObject with a .read that is like reading both files as one.

Any ideas existing workarounds? Yes, I know I can build my own little class or cat files together. Just wondering if there is some magic FileObject joiner I've never heard of.

like image 295
mathtick Avatar asked Oct 16 '25 16:10

mathtick


2 Answers

If your library reads from a file with .read(), there isn't much point in some abstraction of merging multiple file-objects as one. it is quite trivial to read everything and throw it into StringIO.

like image 73
thkang Avatar answered Oct 18 '25 06:10

thkang


if you just want to call readline() on the files, try this:

def cat(*args):
    for arg in args:
        with open(arg,'r') as f:
            for line in f:
                yield line

for line in cat('/tmp/x1','/tmp/x2'):
    processLine(line)
like image 36
Hal Canary Avatar answered Oct 18 '25 08:10

Hal Canary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!