python实现将字符串输出到txt文件中,并合并多个txt文件
将目标内容输出到指定txt文件中
from datetime import datetime
path = 'D:\\test\\test.txt'
with open(path, 'r+', encoding='UTF-8') as file0:
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), file=file0)
print('测试内容', file=file0)
print('测试成功', file=file0)
file0.close()
多个txt文件合并成一个txt
import os
dirPath = 'C://Users//xxx//Desktop'
files = os.listdir(dirPath)
res = ""
i = 0
for file in files:
if file.endwith(".txt"):
print(file)
i += 1
title = "第%s个文件 %s" %(i, file[0:len(file)-4)])
with open("C://Users//xxx//Desktop//" + file, "r", encoding='UTF-8') as file:
content = file.read()
file.close()
append = "\n%s\n\n%s" % (title, content)
res += append
with open("C://Users//xxx//Desktop//test//combination.text", 'w', encoding='UTF-8') as outFile:
outFile.write(res)
outFile.close()