我在命令行中执行的操作:
cat file1 file2 file3 > myfile
我想用python做什么:
import subprocess, shlex my_cmd = 'cat file1 file2 file3 > myfile' args = shlex.split(my_cmd) subprocess.call(args) # spits the output in the window i call my python program
要复制使用 Python 将多个文件串联为一个文件的命令行行为,您可以使用模块subprocess,但需要稍微shlex.split()正在拆分整个命令,subprocess.call()。
subprocess
shlex.split()
subprocess.call()
相反,你应该
subprocess.run()
该subprocess.run()方法提供
import subprocess # Define the command and its arguments command = comm 'cat file1 file2 file3' # Run the command and redirect output to 'myfile' with open('myfile', 'w') as outfile: subprocess.run(command, shell= subprocess.run(command, shel True, stdout=outfile)
shell=True
>
stdout=outfile
myfile
如果你想避免使用shell=True,你可以实现
import subprocess # Define the input files and output file input_files = ['file1', 'file2', 'file3'] output_file = 'myfile' # Concatenate the files with open(output_file, 'wb') as outfile: for file_name in input_files: wi with open(file_name, 'rb') as infile: outfile.write(infile.read()) outfile.write(infile.rea
这种方法以二进制形式读取每个文件