【问题标题】:python concatenate files using subprocess [duplicate]python使用子进程连接文件[重复]
【发布时间】:2013-06-25 15:21:03
【问题描述】:

我一直在搜索,虽然我发现关于如何让 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”

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

【问题讨论】:

    标签: python linux concatenation


    【解决方案1】:

    因为>是一个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)
    

    【讨论】:

      【解决方案2】:

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

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

      但是你必须注意代码注入。

      【讨论】:

      • 酷!这工作得更快。那么使用 subprocess 有什么区别呢?
      • 好答案(+1) 我只是对子进程做了同样的事情
      • 这里你正在运行一个 shell,所以它更慢并且更容易出现安全风险
      【解决方案3】:

      看到这个question。他的解决方案似乎简洁易懂,我就贴在这里:

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

      【讨论】:

      • 谢谢斯蒂芬。这确实有效,我已经看到了。只是当您有超过 10k 或更多行的文本文件时,它会占用 CPU 大量资源:( 我想使用 linux 更快的 cat 功能。
      • this 似乎是一些真正优化的连接@StudentOfScience
      • 我只是用我的大文件运行它,花了 1 分 34 秒。当我手动使用 cat 时(减去我输入代码)需要 24 秒。因此。并不是说我没有额外的 1 分 10 秒可以给,而是作为一个学习使用子进程或 python 到 linux 的机会,我问了这个问题。谢谢。
      • this 将帮助您学习使用子流程进行连接的机会
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 2013-06-13
      • 2012-09-18
      • 2014-04-29
      相关资源
      最近更新 更多