首页 > 解决方案 > 如何在单元格中将txt文件转换为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)

标签: pythoncsv

解决方案


Question: to convert a txt file to csv file in cells

Example using 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()))

Output:

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

推荐阅读