如何加入目录中的所有 txt 文件? (尊重所有行都在另一行之下)
How to join all the txt files that are inside a directory? (Respecting that all lines are one below the other)
我使用此代码列出指定路径目录中的所有那些 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
尝试阅读文件...:[=11=]
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))
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()
我使用此代码列出指定路径目录中的所有那些 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
尝试阅读文件...:[=11=]
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))
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()