Home  >  Article  >  Backend Development  >  An example of Python batch merging of multiple txt files

An example of Python batch merging of multiple txt files

不言
不言Original
2018-05-08 16:15:072802browse

这篇文章主要介绍了关于Python 批量合并多个txt文件的实例讲解,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

实例如下所示:

# -*- coding:utf-8 -*- 
 
#os模块中包含很多操作文件和目录的函数 
import os 
#获取目标文件夹的路径 
meragefiledir = os.getcwd()+'\\MerageFiles'
#获取当前文件夹中的文件名称列表 
filenames=os.listdir(meragefiledir) 
#打开当前目录下的result.txt文件,如果没有则创建
file=open('result.txt','w') 
#向文件中写入字符 
 
#先遍历文件名 
for filename in filenames: 
  filepath=meragefiledir+'\\'
  filepath=filepath+filename
  #遍历单个文件,读取行数 
  for line in open(filepath): 
    file.writelines(line) 
  file.write('\n') 
#关闭文件 
file.close()

相关推荐:

基于python批量处理dat文件及科学计算的方法


The above is the detailed content of An example of Python batch merging of multiple txt files. For more information, please follow other related articles on the PHP Chinese website!

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