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
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
or
as pointed by 1_CR (Thanks) and explained here Python: How to Redirect Output with Subprocess?
Use the
fileinput
module:Use fileinput. Say you have a python file
merge.py
with the following code, you could call it like somerge.py dir/*.txt
. Filemerged.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