【问题标题】:Python - joining text files in multiple subfoldersPython - 在多个子文件夹中加入文本文件
【发布时间】:2020-07-12 16:30:14
【问题描述】:

我有一个包含多个子文件夹的文件夹。在每个子文件夹中,我有多个 .txt 文件。

for root, dirs, files in os.walk(path):
    print(files)
Out:
['1.txt', '2.txt', '3.txt', '4.txt']
['1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt', '7.txt', '8.txt']
['1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt']
['1.txt', '2.txt', '3.txt', '4.txt', '5.txt']

我想加入每个子文件夹中的文本文件并将每个文件作为单个字符串返回。

我尝试了以下方法:

for root, dirs, files in os.walk(path):
    for file in files:
        if file.endswith('.txt'):
            with open(os.path.join(root, file), 'r') as f:
                text = f.read()

但是,我将每个 txt 文件的文本作为单独的字符串获取。我希望它们在每个子文件夹的列表中(如上)或将子文件夹中的每个 txt 加入单个字符串并获得 4 个字符串而不是 23 个字符串的输出。

【问题讨论】:

    标签: python string list file directory


    【解决方案1】:

    您可以像这样在每次读取迭代中使用字符串连接:

    for root, dirs, files in os.walk(path):
        text = ''
        for file in files:
            if file.endswith('.txt'):
                with open(os.path.join(root, file), 'r') as f:
                    text += f.read()
        print(text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多