python讀取多個TXT(包含爲空)寫入一個TXT

需要合併文件如圖:

文件內容如下:

存在特殊情況(文件可能存在空),需要寫入"0 0 0 0":

import os

flie_path="/home/"#需要合併的txt文件的絕對路徑,由於要排序,後面會加上.txt
path_list=os.listdir(flie_path)
path_name=[]
for i in path_list:
    path_name.append(i.split(".")[0])
#文件讀入時是亂序的,需要按0001.txt,0002.txt順序寫入,sort排序
path_name.sort()
i=1
for i in range(len(path_name)):
    path_name1=flie_path+path_name[i]+'.txt'
    print path_name1
    with open(path_name1) as f:
        #文件爲空的情況,寫入"0 0 0 0",並轉行
        if not os.path.getsize(path_name1):
            with open("/home/new.txt",'a+') as mom:#新的txt文件路徑
                line="0 0 0 0"
                mom.write(line)
                mom.write('\r\n')
        #文件不爲空則寫入讀取到的內容
        for line in f.readlines():

            with open("/home/new.txt",'a+') as mom:/home/new.txt
                mom.write(line)

os.path.getsize()返回文件的字節數,如果爲0,則代表空

#如果不是爲1,也就是爲0的時候
if not os.path.getsize(path_name1):

最後結果(如果不注意文件爲空的情況,則會出現合併後新文件行數少於舊的文件數情況)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章