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

2019-03-03 09:54发布

This question already has an answer here:

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

3条回答
虎瘦雄心在
2楼-- · 2019-03-03 10:06

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?

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-03 10:06

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()
查看更多
Melony?
4楼-- · 2019-03-03 10:22

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)
查看更多
登录 后发表回答