如何在单元格中将txt文件转换为csv文件

时间:2019-02-15 18:50:45

标签: python csv

我正在尝试将txt文件转换为以下格式:

NOTE
Date : 2/12/2019
Name : SomeName
Amount : 9000.0
Total : 59000.0
3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx

对于csv文件,省略NOTE并采用单元格格式:

Date,Name,Amount,Total,Signature
2/12/2019, SomeName,9000,59000,3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx

到目前为止,我已存档要做的是:

Date,Number,Amount,Total,Signature
['NOTE'],"['Date', '2/12/2019']","['Name', 'SomeName']","['Amount', '9000.0']","['Total', '59000.0']",['3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx']

这是我的代码:

with open('example.txt', 'r') as in_file:
    stripped = [line.replace(":","").split() for line in in_file]
    zipped = zip([stripped]*1)
    with open('out_file.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('Date', 'Number', 'Amount', 'Total', 'Signature'))
        for group in zipped:
            writer.writerows(group)

2 个答案:

答案 0 :(得分:1)

  

问题:将txt文件转换为单元格中的csv文件

使用csv.DictWriter的示例。

import io, csv

TXT = """NOTE
Date : 2/12/2019
Name : SomeName
Amount : 9000.0
Total : 59000.0
3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx
NOTE
Date : 2/12/2019
Name : SomeName
Amount : 9000.0
Total : 59000.0
3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx
"""

with io.StringIO(TXT) as in_file,\
    io.StringIO() as out_file:

    fieldnames = ['Date', 'Name', 'Amount', 'Total', 'Signature']
    writer = csv.DictWriter(out_file, fieldnames=fieldnames)
    writer.writeheader()

    while True:
        data = {}
        for row in range(6):
            try:
                line = next(in_file)
                s = line.rstrip().split(':')

                if len(s) == 2:
                    data[s[0].strip()] = s[1].strip()
                else:
                    data['Signature'] = s[0]

            except StopIteration:
                break

        if data:
            writer.writerow(data)
        else:
            break

    print('{}'.format(out_file.getvalue()))
  

输出

Date,Name,Amount,Total,Signature
2/12/2019,SomeName,9000.0,59000.0,3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx
2/12/2019,SomeName,9000.0,59000.0,3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx

答案 1 :(得分:0)

格式如何更改? (就像可能发生的变化一样。)


import csv
with open('inp', 'r') as in_file:
    dic = dict()
    a = []
    for line in in_file:
        a.append(line.replace(":","").split())

    a.pop(0) #NOTE
    last = a.pop().pop() #no key
    for i in a:
        dic[i[0]] = i[1]
    with open('out_file.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(dic.keys())
        toWrite = list(dic.values())
        toWrite.append(last)
        writer.writerow(toWrite)

要将“签名”添加到第一行,您需要将dic.keys()更改为列表并在其后附加一个字符串(例如,如果值带有最后一项)

或者像这样:


import csv
with open('inp', 'r') as in_file:
    a = []
    for line in in_file:
        a.append(line.replace(":","").split())

    a.pop(0) #NOTE
    with open('out_file.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('Date', 'Number', 'Amount', 'Total', 'Signature'))
        toWrite = []
        for i in a:
            toWrite.append(i.pop())
        writer.writerow(toWrite)