0

我一直在搜索,虽然我发现关于如何简单地让 python 让 linux 使用 cat 函数将文件连接到单个文件的冗长而复杂(许多我不需要的功能)。

从我的阅读显然 subprocess 是做到这一点的方法。这是我所拥有的,但显然不起作用:(

subprocess.call("cat", str(myfilelist[0]), str(myfilelist[1]), str(myfilelist[2]), str(myfilelist[3]), ">", "concatinatedfile.txt"])

以上假设:

myfilelist[]

上面的列表有 4 个文件名 + 路径作为列表;例如,列表中的一项是“mypath/myfile1.txt”

我也会采用非子流程(但简单)的方法

4

3 回答 3

4

如果你想使用 cat 和重定向 > 你必须调用一个 shell,例如通过系统:

from os import system
system("cat a.txt b.txt > c.txt")

但是,您必须注意代码注入。

于 2013-06-27T23:27:08.223 回答
4

因为> 是你需要做的shell函数shell=True

subprocess.call("echo hello world > some.txt",shell=True)...至少在 Windows 中工作

或者你可以做一些像

with open("redirected_output.txt") as f:
    subprocess.call("/home/bin/cat some_file.txt",stdout=f)
于 2013-06-27T23:30:16.630 回答
2

看到这个问题。他的解决方案似乎简洁易懂,我将在此处发布:

filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read())
于 2013-06-27T23:16:45.993 回答