How to merge multiple txt files in a folder in Python?
漂亮男人
漂亮男人 2017-05-18 10:54:10
0
1
1112

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

漂亮男人
漂亮男人

reply all(1)
我想大声告诉你

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template