[英]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.