[英]How can I load and merge several .txt files in a memory efficient way in python?
[英]How can I merge several txt files into one including their names (with python)?
我想用 Python 將幾個 txt 文件合並到一個文件中。 我已經找到了一個代碼:
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())
但我想保留單個 txt 文件的名稱,並將它們打印在合並文件中的每個 txt 文件上方。 知道如何解決嗎?
這應該工作
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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.