Python implementation method for merging all TXT files under the same folder

Source: Internet
Author: User
This article mainly describes the Python implementation of merging all TXT files under the same folder method, involving Python for file traversal, read, write and other related operations skills, the need for friends can refer to the following

This example describes how Python implements all txt files in the same folder. Share to everyone for your reference, as follows:

First, demand analysis

Merge all txt files under a folder

Second, the merger effect

Third, Python implementation code

#-*-Coding:utf-8*-import sysreload (SYS) sys.setdefaultencoding (' utf-8 ') import osimport os.pathimport timetime1= Time.time () ######################### #合并同一个文件夹下多个txt ############### #def mergetxt (filepath,outfile):  k = open ( Filepath+outfile, ' A + ') for  the parent, dirnames, filenames in Os.walk (filepath): for    filepath in filenames:      Txtpath = Os.path.join (parent, filepath) # Txtpath is the path to all folders      f = open (Txtpath)      ######### #换行写入 ################ # #      K.write (F.read () + "\ n")  k.close ()  print "finished" if __name__ = = ' __main__ ':  filepath= "D:/course /"  outfile=" Result.txt "  mergetxt (filepath,outfile)  time2 = Time.time ()  print U ' total time: ' + str ( TIME2-TIME1) + ' s '

Operation Result:

"D:\Program Files\python27\python.exe" d:/pycharmprojects/learn2017/merging multiple txt.py
Finished
Total time: 0.000999927520752s
Process finished with exit code 0

More Python-related content readers can view this site topic: "Python text file Operation tips Summary", "Python File and directory Operation skills Summary", "Python Coding skills Summary", "Python data structure and algorithm tutorial", " Python function Usage Tips Summary, python string manipulation tips summary and Python Introductory and advanced Classic tutorial

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.