如何加入目录内的所有txt文件? (尊重所有行都在另一行之下)[重复]

Posted

技术标签:

【中文标题】如何加入目录内的所有txt文件? (尊重所有行都在另一行之下)[重复]【英文标题】:How to join all the txt files that are inside a directory? (Respecting that all lines are one below the other) [duplicate] 【发布时间】:2021-11-02 20:06:52 【问题描述】:

我使用此代码列出指定路径目录中的所有 txt

from glob import glob

path_directory = 'Part001/*.txt'
list_files = glob(path_directory)

for f in list_files:
    print(f)

我需要帮助才能将所有列出的 txt 合并为一个包含所有文本行的单个 txt。像这样的:

31Aug21.txt

Hello
Hello!
Hello, Tell me about something

04Sep21.txt

Computer equipment has evolved in recent decades.
Perfect Orbit

05Sep21.txt

The sky is blue
the computer is really useful

并且列出的txt的所有行都应该写在一个新的txt中,像这样:

Hello
Hello!
Hello, Tell me about something
Computer equipment has evolved in recent decades.
Perfect Orbit
The sky is blue
the computer is really useful

【问题讨论】:

【参考方案1】:
from glob import glob

path_directory = 'Part001/*.txt'
list_files = glob(path_directory)

final = open('final_file.txt')
for f in list_files:
    with open(f) as fo:
        text = fo.read()
    final.write(text) #can add \n after this if you want - text+'\n'

final.close()

【讨论】:

【参考方案2】:

通过读取文件试试这个...:

from glob import glob

path_directory = 'Part001/*.txt'
list_files = glob(path_directory)

lst = []
for fname in list_files:
    with open(fname, 'r') as f:
        lst.append(f.read())

with open('newfile.txt', 'w') as newf:
    newf.write('\n'.join(lst))

【讨论】:

以上是关于如何加入目录内的所有txt文件? (尊重所有行都在另一行之下)[重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何把一个文件夹中所有文件的文件名导出

将 txt 文件合并为一个文件,然后再次拆分它们

批处理删除当前文件夹下所有指定类型文件(包括子目录)

易语言 如何 列出 指定目录下 所有 文件名

如何使用'ls'列出根目录和子目录中的所有文本文件

如何重写历史记录,以便除我已经移动的文件之外的所有文件都在子目录中?