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

这一生的挚爱 提交于 2019-12-02 12:28:01
user2390183

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?

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()

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!