Home  >  Q&A  >  body text

How to merge multiple txt files in a folder in Python?

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

漂亮男人漂亮男人2711 days ago1083

reply all(1)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-18 10:56:10

    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)

    reply
    0
  • Cancelreply