How to merge multiple txt files in a folder in Python?
漂亮男人2017-05-18 10:54:10
0
1
1101
Read a txt file in the folder Record the txt file name (user ID) Write to a new txt file Delete the original txt file Loop of the above steps txt files are sorted by time in the content Add user ID at the beginning of each log Original content
Python2.7 syntax, please change it accordingly for py3
import glob
import os
src_dir = '/root/*.txt' # 利用通配符查找后缀名为txt的文件
dest_file = 'result.txt'
with open(dest_file, 'w') as f_w:
for file_name in glob.glob(src_dir):
with open(file_name) as f_r:
for line in f_r:
f_w.write('%s %s' % (file_name, line))
os.remove(file_name)
Python2.7 syntax, please change it accordingly for py3