Unix cat function (cat * > merged.txt) in Python?

2019-03-03 09:20发布

问题:

This question already has an answer here:

  • Reproduce the Unix cat command in Python 6 answers

Is there a way to use the cat function from Unix in Python or something similar once a directory has been established ? I want to merge files_1-3 together into merged.txt

I would usually just find the directory in Unix and then run

cat * > merged.txt 

file_1.txt
file_2.txt
file_3.txt

merged.txt

回答1:

As we know we are going to use "Unix" cat command (unless you are looking for a pythonic way or being performance concious)

You can use

import os
os.system("cd mydir;cat * > merged.txt")

or

as pointed by 1_CR (Thanks) and explained here Python: How to Redirect Output with Subprocess?



回答2:

Use the fileinput module:

import fileinput
import glob
with open('/path/to/merged.txt', 'w') as f:
    for line in fileinput.input(glob.glob('/path/to/files/*')):
        f.write(line)
    fileinput.close()


回答3:

Use fileinput. Say you have a python file merge.py with the following code, you could call it like so merge.py dir/*.txt. File merged.txt gets written to current dir. By default, fileinput iterates over the list of files passed on the command line, so you can let the shell handle globbing

#!/usr/bin/env python
import fileinput
with open('merged.txt', 'w') as f:
    for line in fileinput.input():
        f.write(line)