阅读csv文件auto delimeter

时间:2018-05-29 14:08:37

标签: python-3.x csv python-3.6

我有一个小脚本,可以读取管道'|'分隔的csv文件,然后以逗号分隔的方式将其写入另一个文件。它工作正常。代码,输入文件和输出文件如下:

import csv


ifile = "d:\\python\\project\\cars-original.csv"
ofile = "d:\\python\\project\\cars.csv"

with open(ifile, 'r') as f:
    reader = csv.reader(f, delimiter='|')
    with open(ofile, 'w', newline='') as of:
        writer = csv.writer(of, delimiter=',')
        for row in reader:
            writer.writerow(row)

Reading|Make|Model|Type|Value Reading 0|Toyota|Previa|distance|19.83942 Reading 1|Dodge|Intrepid|distance|31.28257 Reading,Make,Model,Type,Value Reading 0,Toyota,Previa,distance,19.83942 Reading 1,Dodge,Intrepid,distance,31.28257

我现在想要修改脚本,以便它可以自动读取分隔符类型。

我在网上找到了几个例子,但是当我运行我的时候,我得到一个空白文件输出。没有错误,只是空白。不确定我做错了什么。

我的修改(损坏)脚本:

import csv


ifile = "d:\\python\\projects\\cars-original.csv"
ofile = "d:\\python\\projects\\cars.csv"


with open(ifile, 'r') as f:
    reader = csv.reader(f)
    dialect = csv.Sniffer().sniff(f.read(1024), delimiters=',|')
    with open(ofile, 'w', newline='') as of:
        writer = csv.writer(of, dialect)
        for row in reader:
            writer.writerow(row)

2 个答案:

答案 0 :(得分:1)

在Python文档(https://docs.python.org/3.6/library/csv.html)的示例中,文件指针在方言检测后立即移动到文件的开头。

with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)

答案 1 :(得分:1)

这有效:

import csv


ifile = "d:\\python\\project\\cars-original.csv"
ofile = "d:\\python\\project\\cars.csv"


with open(ifile, 'r') as f:
    dialect = csv.Sniffer().sniff(f.readline(), [',', '|'])
    f.seek(0)
    reader = csv.reader(f, dialect)
    with open(ofile, 'w', newline='') as of:
        writer = csv.writer(of, delimiter=',')
        for row in reader:
            writer.writerow(row)