[英]Python merge multiple txt files
我尝试使用此代码合并一个文件夹中的多个TXT文件,但无法正常工作:
import os,shutil
path = "C:/Users/user/Documents/MergeFolder"
f=open(path + "/fileappend.txt","a")
for r,d,fi in os.walk(path):
for files in fi:
if files.endswith(".txt"):
g=open(os.path.join(r,files))
shutil.copyfileobj(g,f)
g.close()
f.close()
有人有主意吗?
编辑:您要创建fileappend.txt
内path
,一边写它。 根据将写入内容刷新到磁盘的时间,您可能正在尝试读取要附加到的文件。 这会引起很多奇怪。 考虑不要将fileappend.txt
放置在path
,或者在完成后仅将其移动到该位置。
您可以将代码更简洁地编写为:
with open(os.path.join(path, "fileappend.tmp"), "a") as dest:
for _, _, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, "*.txt"):
with open(filename) as src:
shutil.copyfileobj(src, dest)
os.rename(os.path.join(path, "fileappend.tmp"), "fileappend.txt")
你可以使用cat(shell命令)
cat 1.txt>>2.txt
在python中,您可以使用os.system()来使用shell命令
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.