Method code for merging multiple files into one text file using Python

Method code for merging multiple files into one text file using Python

Python file processing is convenient and fast. This article provides you with a code example on how to use Python to merge multiple text files . To merge multiple txt or other types of files into one, manual operation is time-consuming and laborious. It is better to write a python code yourself to complete it once and for all.

It is not difficult to complete the py code of this merged file. You only need to know some basic python functions , file reading and writing judgment and other methods to achieve it. You can have a brief understanding of the article commonly used built-in methods of Python file objects on Wanshen.com .

The code for merging multiple files into one text file using Python is as follows:

# coding gbk  
  
import sys,os,msvcrt  #导入的模块与方法
   
def join(in_filenames, out_filename):  
    out_file = open(out_filename, 'w+')  
       
    err_files = []  
    for file in in_filenames:  
        try:  
            in_file = open(file, 'r')  
            out_file.write(in_file.read())  
            out_file.write('\n\n')  
            in_file.close()  
        except IOError:  
            print 'error joining', file 
            err_files.append(file)  
    out_file.close()  
     
    print 'joining completed. %d file(s) missed.' % len(err_files)  
     
    print 'output file:', out_filename  
     
    if len(err_files) > 0:  #判断
        print 'missed files:' 
        print '--------------------------------' 
        for file in err_files:  
            print file 
        print '--------------------------------' 
#www.iplaypy.com  
if __name__ == '__main__':  
    print 'scanning...' 
    in_filenames = []  
    file_count = 0 
     
    for file in os.listdir(sys.path[0]):  
        if file.lower().endswith('[all].txt'):  
            os.remove(file)  
        elif file.lower().endswith('.txt'):  
            in_filenames.append(file)  
            file_count = file_count + 1 
     
    if len(in_filenames) > 0:  
        print '--------------------------------' 
        print '\n'.join(in_filenames)  
        print '--------------------------------' 
        print '%d part(s) in total.' % file_count  
        book_name = raw_input('enter the book name: ')  
        print 'joining...' 
        join(in_filenames, book_name + '[ALL].TXT')  
    else:  
        print 'nothing found.' 
     
    msvcrt.getch()

The python code for merging files above uses the python sys module  , python os module , msvcrt and other module methods. It is recommended to have a proper understanding before reading the code to make it easier to understand.

Guess you like

Origin blog.csdn.net/lmrylll/article/details/131961806