【问题标题】:Concatenating multiple .txt in files in subdirectories在子目录中的文件中连接多个 .txt
【发布时间】:2014-04-22 13:53:57
【问题描述】:

我在不同级别的子目录中有多个 .txt 文件。所有 txt 文件都在最终迭代中,即 .txt 文件和其他目录都没有级别。我想将它们全部连接到一个新的文本文件中,但找不到一种简单的方法来遍历所有子目录。

我找到的一个命令,就是这样输入到python命令行终端的:

$ cat source/file/*.txt > source/output/output.txt

但我不确定如何让这个迭代多个子目录。 (我是一个真正的python初学者,似乎有些困惑。这不是python命令吗?我找到它的来源声称它是......)

【问题讨论】:

  • 我没看到 Python 和这个有什么关系?
  • cat 不是 Windows 实用程序。
  • 如果您说的是 Windows 7 中的 Cygwin,find /source/dir -name *.txt -exec cat {} >> /destination/dir/output.txt \; 应该可以工作。
  • 我更喜欢find source_dir -name "*.txt" -type f | xargs cat > output.file.txt(不会在每个文件上都开始新的猫)
  • @Henry 请说清楚,如果您正在寻找 cygwin 解决方案,或纯 windows 命令行(那里没有 cat)。

标签: python file windows-7 cat


【解决方案1】:

您可以使用 python 脚本构建它们,例如:

file_list = ['c:\data.txt', 'c:\folder1\data.txt']

for everything in file_list:
    f = open(everything)
    for line in f.readlines():
        print line

从 cmd 调用脚本,例如\python.exe 'buildtxtfiles.py'

【讨论】:

  • file_list 是否只需要包含顶级文件夹,还是必须列出所有目录和子目录?有成千上万的子目录,我正在寻找一种可以为我遍历它们的解决方案,而不必提前定义一个列表......
猜你喜欢
  • 2019-09-19
  • 2010-12-06
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-24
  • 1970-01-01
相关资源
最近更新 更多