如何加入目录内的所有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文件? (尊重所有行都在另一行之下)[重复]的主要内容,如果未能解决你的问题,请参考以下文章