我尝试用下面的代码合并文件夹中的多个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()有谁有主意吗?
发布于 2012-11-23 17:41:37
编辑:在path中创建fileappend.txt,同时对其进行写入。根据写入刷新到磁盘的时间,您可能正在尝试读取要追加的文件。这会导致,嗯,很多奇怪的事情。考虑不要将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")发布于 2017-05-08 18:04:28
您可以使用cat(shell命令)
cat 1.txt>>2.txt在python中,您可以使用os.system()来使用外壳命令
https://stackoverflow.com/questions/13525847
复制相似问题