I want to merge several txt files into one file with Python. I already found a code for that:
import glob
read_files = glob.glob("*.txt")
with open("result.txt", "wb") as outfile:
for f in read_files:
with open(f, "rb") as infile:
outfile.write(infile.read())
But I want to keep the names of the single txt files and have them printed above each txt file in the merged one. Any idea how to solve that?
This should work
import glob
read_files = glob.glob("*.txt")
with open("result.txt", "wb") as outfile:
for f in read_files:
with open(f, "rb") as infile:
outfile.write(bytes(f"{f}\n", 'utf-8'))
outfile.write(infile.read())
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.