用Python合并多个文件为一个文本文件的方法代码
Python文件处理操作方便快捷,本文为大家提供的是如何用Python合并多个文本文件的代码示例。要把多个txt或是其它类型文件合并成一个,手动操作费时费力,不如自己动手写一个python代码来完成,一劳永逸。
要完成这个合并文件的py代码并不难,只需要会一些基本的python函数,文件读写判断等方法就可以实现。玩蛇网的Python 文件对象常用内建方法一文大家可以去简单的了解下。
用Python合并多个文件为一个文本文件的方法代码如下:
# 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()
上面合并文件的python代码中用到了python sys模块 ,python os模块,msvcrt等模块方法,都建议适当了解下之后再看代码更容易理解。