20171026python读取txt写入csv

import csv

def get_lines(filepath):
    with open(filepath) as file_object:
        lines=set(file_object.readlines())
        return lines
    
def new_csv(lines):
    fileindex=0
    count=len(lines)
    print("总行数"+str(count))
    for index,line in enumerate(lines):
        index+=1
        #print(str(index)+'_'+line)
        oneline=line.strip()#逐行读取,剔除空白
        if (index-1) % 1000 +1 ==1:
            data=[]
            if len(oneline)==11:
                data.append([oneline])
        elif index % 1000 ==0 or index==count:
            fileindex+=1
            if len(oneline)==11:
                data.append([oneline])
            with open(str(fileindex)+'.csv','w') as csvfile:
                csv_writer=csv.writer(csvfile,dialect='excel')
                #csv_writer=csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
                csv_writer.writerows(data)
        else:
            if len(oneline)==11:
                data.append([oneline])
if __name__ == "__main__":
    filepath="Text.txt"
    lines=get_lines(filepath)
    new_csv(lines)

  

posted @ 2017-10-26 10:47  wangway  阅读(4085)  评论(0编辑  收藏  举报