Home  >  Article  >  Backend Development  >  Python实现将目录中TXT合并成一个大TXT文件的方法

Python实现将目录中TXT合并成一个大TXT文件的方法

WBOY
WBOYOriginal
2016-06-10 15:09:151326browse

本文实例讲述了Python实现将目录中TXT合并成一个大TXT文件的方法。分享给大家供大家参考。具体如下:

在网上下了一个dota的英雄攻略,TXT格式,每个英雄一个文件,看得疼,就写了一个小东西,合并一下.

#coding=gbk
import os
import sys
import glob
def dirTxtToLargeTxt(dir,outputFileName):
  '''从dir目录下读入所有的TXT文件,将它们写到outputFileName里去'''
  #如果dir不是目录返回错误
  if not os.path.isdir(dir):
    print "传入的参数有错%s不是一个目录" %dir
    return False
  #list all txt files in dir
  outputFile = open(outputFileName,"a")
  for txtFile in glob.glob(os.path.join(dir,"*.txt")):
    print txtFile
    inputFile = open(txtFile,"rb")
    for line in inputFile:
      outputFile.write(line)
  return True
if __name__ =="__main__":
  if len(sys.argv) < 3:
    print "Usage:%s dir outputFileName" %sys.argv[0]
    sys.exit()
  dirTxtToLargeTxt(sys.argv[1],sys.argv[2])

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn