使用不常见的分隔符使用Python 3

时间:2018-04-04 18:51:32

标签: python-3.x parsing

我有一个.txt文件:

16A:0617XXXXX
17B:560-L
18C:AID0005345

我试图使用一个不常见的分隔符将一个单元格解析为两个单元格,冒号':'。

我尝试按照简单的解析指南,我的代码是:

with open('/u/ISIN.txt', 'r') as ISIN_file:
    csv_reader = csv.reader(ISIN_file)

    with open('/u/ISIN_new.txt', 'w') as ISIN_file_new:
        csv_writer = csv.writer(ISIN_file_new, delimiter=':')

        for line in csv_reader:
            csv_writer.writerow(line)

问题是,当新文件与旧文件相同时。我想知道使用非标准分隔符是否存在问题?

1 个答案:

答案 0 :(得分:1)

此代码:

import csv

with open('jay.txt') as jay:
    csv_reader = csv.reader(jay, delimiter=':')
    with open('jay.csv', 'w', newline='') as jay_out:
        csv_writer = csv.writer(jay_out)
        for line in csv_reader:
            csv_writer.writerow(line)

产生这个结果:

16A,0617XXXXX
17B,560-L
18C,AID0005345