用python中的子进程和通配符连接文件列表
我正在尝试将目录中的多个文件连接到单个文件。到目前为止,我一直在尝试将cat与子流程一起使用,但效果不佳 我最初的代码是:用python中的子进程和通配符连接文件列表,python,subprocess,Python,Subprocess,我正在尝试将目录中的多个文件连接到单个文件。到目前为止,我一直在尝试将cat与子流程一起使用,但效果不佳 我最初的代码是: source = ['folder01/*', 'folder02/*'] target = ['/output/File1', '/output/File2'] for f1, f2, in zip(source, target): subprocess.call(['cat', f1, '>>', f2]) 我试过把它交给shell=True:
source = ['folder01/*', 'folder02/*']
target = ['/output/File1', '/output/File2']
for f1, f2, in zip(source, target):
subprocess.call(['cat', f1, '>>', f2])
我试过把它交给shell=True:
..., f2], shell=True)
并与subprocess.Popen结合使用,而不是调用许多排列,但没有乐趣
正如我从其他类似问题中了解到的,如果shell=True,则需要将命令作为字符串提供。在以字符串形式执行时,如何对列表中的所有项目调用cat?此处不需要子进程,并且必须尽可能避免使用子进程,这意味着:99.99%的时间
正如评论中所指出的,也许我应该花几分钟和要点向您解释原因:
使用subprocess或类似工具时,假设您的代码将始终在完全相同的环境中运行,这意味着相同的操作系统、版本、shell、安装的工具等。。这实际上不适用于生产等级代码。
这类库将阻止您生成pythonicpython代码,您必须通过解析字符串而不是try/except等来处理错误。。
蒂姆·彼得斯(Tim Peters)写了《Python之禅》,我鼓励大家遵循它,这里至少有三点是相关的:美丽胜于丑陋,可读性很重要。简单总比复杂好。。
换句话说:子流程只会降低代码的健壮性,迫使您处理非Python问题,迫使您执行复杂的计算,您只需编写干净而强大的Python代码
有很多很好的理由不使用子流程,但我认为你明白了
仅使用open打开文件,以下是您需要调整的基本示例:
import os
for filename in os.listdir('./'):
with open(filename, 'r') as fileh:
with open('output.txt', 'a') as outputh:
outputh.write(fileh.read())
针对您的特定需求的实施示例:
import os
sources = ['/tmp/folder01/', '/tmp/folder02/']
targets = ['/tmp/output/File1', '/tmp/output/File2']
# Loop in `sources`
for index, directory in enumerate(sources):
# Match `sources` file with expected `targets` directory
output_file = targets[index]
# Loop in files within `directory`
for filename in os.listdir(directory):
# Compute absolute path of file
filepath = os.path.join(directory, filename)
# Open source file in read mode
with open(filepath, 'r') as fileh:
# Open output file in append mode
with open(output_file, 'a') as outputh:
# Write content into output
outputh.write(fileh.read())
小心,我更改了您的源和目标值/tmp/您将执行string=cat{}>{}.formatf1、f2在这里为您提供了一些帮助:我一直在尝试集成此解决方案。到目前为止,我有:对于zipsource中的f1、f2,目标:对于os.listdirf1中的文件名:使用openfilename,'r'作为文件H:使用openf2,'a'作为outputh:outputh.writefileh.read,这似乎可以工作,但它在错误的位置查找文件。我以前从未使用过os.listdir-如何让它写入列表的完整路径而不仅仅是文件名?没关系,你早就料到我的问题了,还抢在我前面!非常感谢。:,您也可以使用,但我更喜欢os.listdir。在这一点上,我可能是错的,所以请看一些文档并做出选择。答案非常清晰简洁。完美集成了解决方案,谢谢@JoelCornett祝Joel长寿