I tried to merge multiple TXT-files in a folder with this code but it is not working:
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()
Anyone has an idea?
EDIT: you're creating fileappend.txt
inside path
, while writing to it. Depending on when the writes are flushed to disk, you may be trying to read the file that you're appending to. This would cause, well, lots of weirdness. Consider not placing fileappend.txt
inside path
, or else just moving it there when you're done.
You can write your code more neatly as:
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")
you can use cat(shell command)
cat 1.txt>>2.txt
in python, you can use os.system() to use shell command
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.