簡體   English   中英

python從多個文本文件創建列表,並從這些列表創建csv文件

[英]python create lists from multiple text files and create csv file from those lists

碰到一個樹樁,我有兩個舊文本文件,我想從中提取數據以創建一個csv文件。

為了簡短起見,這是我在屏幕上顯示的代碼:

import csv, itertools

list1 = []
with open('D:/py_files/legacy_temp/REPORT_1.TXT', 'rb') as tf:
    for line in tf:
        if len(line) > 2:
            if line[17].isdigit():
                acctnum = str(line[16:31])
                custname = str(line[39:58])
                currbal = str(line[84:96])
                diffbal = str(line[102:114])
                list1.append(acctnum + '|' + custname + '|' + currbal + '|' + diffbal)

list2 = []
with open('D:/py_files/legacy_temp/REPORT_2.TXT', 'rb') as tf2:
    for line in tf2:
        if line[0].isdigit():
            acctnum = str(line[1:12])
            ourbal = str(line[80:90])
            alldnum = str(line[123:131])
            clntnum = str(line[132:152])
            list2.append(acctnum + '|' + ourbal + '|' + alldnum + '|' + clntnum)

下面的代碼只是我的剪貼簿,我正在嘗試的事情。 我可以創建csv文件,但是它要么寫成一個連續的長行,要么在附加'|'時寫 在每個字符之后,即:a | b | c | d | 等等...

#mlist = []
#if len(list1) == len(list2):
#   for i, j in map(None,list1,list2):
#       print i + '|' + j
def f1():
    clist = []
    outfile = csv.writer(open('D:/py_files/legacy_temp_/report_diff.csv', 'wb'))
    if len(list1) == len(list2):
        for i, j in map(None,list1,list2):
            clist.append(str(i + '|' + j + '\n'))
        outfile.writerow(clist)
        print '\n'.join(clist)

def f2():
    for x,y in zip(list1,list2):
        print list1+list2
def f3():
    output = list(itertools.chain(list1,list2))
    print '\n'.join(output)

兩件事,a)我是要以正確的方式(分別打開兩個文本文件)來進行操作,b)如果是,我如何編寫一個csv文件,該文件將給我以下行:

acctnum|custname|currbal|diffbal|acctnum|ourbal|alldnum|clntnum

|每個元素 以上,在一個單獨的單元格中。

PS。 我僅將管道用作定界符,因為余額中包含逗號。 我不需要使用管道,因為我可以替換天平中的逗號。

非常感謝所有幫助,謝謝

實際上,原始功能將與第二個功能一起使用,只需稍作修改即可:

def f2():
    for x,y in zip(list1,list2):
        print list1+list2 <-- this should be print x+y

應該將要附加的內容放在方括號中。

list1.append([acctnum + '|' + custname + '|' + currbal + '|' + diffbal])

您也可以這樣做:

list1.append(['|'.join([acctnum, custname, currbal, diffbal])])

然后,您將在list1中獲得一堆列表,它們代表一行。

如果您想以最快,最簡單的方式將數據從txt轉換為csv,則可以執行以下操作:

import csv

header = ('acctnum,custname,currbal,diffbal,acctnum,ourbal,alldnum,clntnum\n')
with open('out.csv', 'wb') as fout:
    fout.write(header)

    with open('blah1.txt', 'rU') as fin1:
        fin1.next()

        for row in fin1:
            fout.write(row.replace('|',','))

    fout.write('\n')

    with open('blah2.txt', 'rU') as fin2:
        fin2.next()

        for row in fin2:
            fout.write(row.replace('|',','))

這將帶走您的兩個文件,並將它們合並為一個CSV,同時還要處理管道定界符。 如果您已經刪除了管道,則只需刪除“ .replace('|',',')”位,以便僅將“行”傳遞給csv編寫器。然后,您可以刪除所有未添加的列想要Excel或其他東西。

謝謝,這是不正確的縮進。

import csv

path = 'D:/py_files/legacy_temp/'

outfile1 = csv.writer(open(path + 'REPORT_1.csv', 'wb'))
with open(path + 'REPORT_1.TXT', 'rb') as f1:
    for line in f1:
        lne = line.replace('\x0c','').replace('\x1c','').replace('\r','').replace('\n','')
        if len(lne) > 2:
            if lne[17].isdigit():
                list1 = []
                list1.append(str(lne[16:31].replace('-','').strip()))
                list1.append(str(lne[39:58].strip()))
                list1.append(str(lne[84:96].strip()))
                list1.append(str(lne[102:114].strip()))
                outfile1.writerow(list1)

outfile2 = csv.writer(open(path + 'REPORT_2.csv', 'wb'))
with open(path + 'REPORT_2.TXT', 'rb') as f2:
    for line in f2:
        lne = line.replace('\x0c','').replace('\x1c','').replace('\r','').replace('\n','')
        if len(lne) > 1:
            if lne[0].isdigit():
                list2 = []
                list2.append(str(lne[1:12].strip()))
                list2.append(str(lne[80:90].strip()))
                list2.append(str(lne[123:131].strip()))
                list2.append(str(lne[132:152].strip()))
                outfile2.writerow(list2)

現在,我正在查看csv文件,我只想合並兩個列表並創建一個csv文件。 它們將始終是相同的長度。 如果不是,則報告有問題。 我將開始工作。

編輯:這是合並的...

import csv

path = 'D:/py_files/legacy_temp/'

with open(path + 'REPORT_MERGE.csv', 'wb') as csvf1:
    writer = csv.writer(csvf1)

    lst1 = []
    with open(path + 'REPORT_1.TXT', 'rb') as f1:
        for line in f1:
            lne = line.replace('\x0c','').replace('\x1c','').replace('\r','').replace('\n','')
            if len(lne) > 2:
                if lne[17].isdigit():
                    list1 = []
                    list1.append(str(lne[16:31].replace('-','').strip()))
                    list1.append(str(lne[39:58].strip()))
                    list1.append(str(lne[84:96].strip()))
                    list1.append(str(lne[102:114].strip()))
                    lst1.append(list1)

                    #creates ['x', 'x', 'x', 'x']

    lst2 = []
    with open(path + 'REPORT_2.TXT', 'rb') as f2:
        for line in f2:
            lne = line.replace('\x0c','').replace('\x1c','').replace('\r','').replace('\n','')
            if len(lne) > 1:
                if lne[0].isdigit():
                    list2 = []
                    list2.append(str(lne[1:12].strip()))
                    list2.append(str(lne[80:90].strip()))
                    list2.append(str(lne[123:131].strip()))
                    list2.append(str(lne[132:152].strip()))
                    lst2.append(list2)

                    #creates ['y', 'y', 'y', 'y']

    for x, y in zip(lst1,lst2):
        writer.writerow(x + y)
        #creates ['x', 'x', 'x', 'x', 'y', 'y', 'y', 'y']
        #each element in merged list writes to its own cell *****

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM