【问题标题】:How to find the all text files from the path and combine all the lines in that text files to one text file如何从路径中找到所有文本文件并将该文本文件中的所有行合并到一个文本文件中
【发布时间】:2016-03-23 17:11:14
【问题描述】:

我有这段代码可以将一个文本文件中的所有行合并到另一个新文本文件中的一行中。 例如: 我有一个包含这些行的文本文件

大学

逃跑

电源

文字

我需要将这些行组合成在线作为

大学转义电源文本

这对我来说很好。

代码:

import os
current = None 
parts = []
with open('input.txt', 'rb') as f:
    for line in f:
        if line.startswith('--'):
            current = [line.strip()]
            parts.append(current)

        elif current is not None:
             current.append(line.strip())


with open('output.txt', 'w+b') as f1:
 for part in parts:
    f1.write('\n'+' '.join(part+' '))

但需要将所有文本文件行合并为一个文本文件。请您指导我。

示例:我的路径中有这些文本文件。

  1. input.txt

  2. 输入 (1).txt

  3. 输入 (2).txt

  4. 输入 (3).txt

【问题讨论】:

    标签: python-2.7


    【解决方案1】:

    您可以像这样读取所有文本文件:

    import os
    
    file_contents = []
    for file in os.listdir("directory_to_search"):
        if file.endswith(".txt"):
            with open('input.txt', 'rb') as f:
                file_contents.append(" ".join(line.strip() for line in f))
    

    这将使用每个文件的内容填充 file_contents,因此现在您可以将它们全部写入输出文件:

    with open('output.txt', 'w+b') as f1:
        all_files_as_one_string = ' '.join(file_contents)
        f1.write(all_files_as_one_string)
    

    请注意,如果您的每个文件中有多个单词,则需要遍历 file_contents 列表并将所有行连接起来,然后再从它们生成单个大字符串。

    【讨论】:

    • 其实我的问题是读取目录下的多个文本文件,并将所有文本文件的行合并到一个文本文件中
    • 啊,好吧,我以为你已经开始工作了。我已经编辑了我的答案以在一个目录中找到所有 txt 文件并将它们组合起来。
    • 谢谢。另外我有一个疑问,我想将一个文本文件中的所有行合并为一行。我该怎么做
    • 我已经编辑了答案,将源文件中的所有行在读入时合并为一个。
    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    相关资源
    最近更新 更多