99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829
麥子學院 頭像
蘋果6袋
6
麥子學院

Python文件操作之合并文本文件內(nèi)容

發(fā)布時間:2017-09-14 23:54  回復:0  查看:3121   最后回復:2017-09-14 23:54  

本文和大家分享的主要是python文件操作中合并文本文件內(nèi)容相關(guān)內(nèi)容,一起來看看吧,希望對大家學習python有所幫助。

  目前一個用的比較多的功能:將多個小文件的內(nèi)容合并在一個統(tǒng)一的文件中,對原始文件重命名標記其已被處理過。

  之前使用其他腳本寫的,嘗試用python寫了一下,順便熟悉一下python的文件處理命令。

  原始文件

Python文件操作之合并文本文件內(nèi)容


經(jīng)過處理之后

Python文件操作之合并文本文件內(nèi)容

最后還有一個蛋疼的因為縮進產(chǎn)生的第一個回車符

  其中包含了文件的創(chuàng)建和移除,文件內(nèi)容的讀寫,文件的重命名的語法命令等等

  # -*- coding: utf-8 -*-

  import os

  import time

  import datetime

  def merge_file(file_path,file_name):

  #file_path must exits

  if(os.path.exists(file_path) is False):

  print('file_path is not exists')

  return

  if(os.path.exists(os.path.join(file_path, file_name))):

  os.remove(os.path.join(file_path, file_name))

  #'%Y_%m_%d%H%M%S',創(chuàng)建一個以日期命名的文本文件

  targetfilename  = str(time.strftime('%Y%m%d%H%M%S'))+'.txt'

  fobj = open(os.path.join(file_path, targetfilename), 'w')

  fobj.close()

  # a 是以追加的方式打開文件寫入

  with open(os.path.join(file_path, targetfilename), 'a', encoding='GBK') as f_wirte:

  files = os.listdir(file_path)

  for file in files:

  print(os.path.join(file_path, file))

  with open(file_path+'\\'+file, 'r', encoding='GBK') as f:

  for line in f.readlines():

  if(line.strip().__len__()) > 0:# 排除空行

  f_wirte.write(line)

  f_wirte.write('\n')# 每讀完一個文件之后,加一個回車,否則第一個文件的最后一行跟第二個文件的第一行沒有回車

  # 文件合并之后,重命名原始的文件,

  # os.path.splitext(file)[0] 提取文件名,不包括后綴名

  # os.path.splitext(file)[0] 提取文件后綴名

  if (file != targetfilename):

  os.rename(os.path.join(file_path, file),os.path.join(file_path, os.path.splitext(file)[0] + '_' +str(time.strftime('%Y%m%d%H%M%S')) +'_已處理' + '.txt'))

  merge_file('D:\TestPythonMergeFile','auoto_create_a_category_file')

 

 

來源:博客園

您還未登錄,請先登錄

熱門帖子

最新帖子

?