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