python - 包含额外逗号的 csv 文件的 CSV 模块问题

标签 python csv

我正在阅读 Clinton W. Brownley (O'Reilly Media Inc.) 的Foundation for Analytics with Python一书

对于第 2 章 - 读取和写入 CSV 文件(第 2 部分) 基本 Python,带有 csv 模块

脚本如下:

#!/usr/bin/env python3
import sys
import csv

input_file = sys.argv[1]
output_file = sys.argv[2]

with open(input_file, 'r', newline='') as csv_input_file:
    with open(output_file, 'w', newline='') as csv_output_file:

        filereader = csv.reader(csv_input_file, delimiter=',')
        filewriter = csv.writer(csv_output_file, delimiter=',')

        for row_list in filereader:
            print(row_list)
            filewriter.writerow(row_list)

输入文件的字段包含逗号(最后两行中的美元金额):

Supplier Name,Invoice Number,Part Number,Cost,Purchase Date
Supplier X,001-1001,2341,$500.00,1/20/14
Supplier X,001-1001,2341,$500.00,1/20/14
Supplier X,001-1001,5467,$750.00,1/20/14
Supplier X,001-1001,5467,$750.00,1/20/14
Supplier Y,50-9501,7009,$250.00,1/30/14
Supplier Y,50-9501,7009,$250.00,1/30/14
Supplier Y,50-9505,6650,$125.00,2/3/14
Supplier Y,50-9505,6650,$125.00,2/3/14
Supplier Z,920-4803,3321,$615.00,2/3/14
Supplier Z,920-4804,3321,$615.00,2/10/14
Supplier Z,920-4805,3321,$6,015.00,2/17/14
Supplier Z,920-4806,3321,$1,006,015.00,2/24/14

运行脚本在终端中产生以下输出:

['Supplier Name', 'Invoice Number', 'Part Number', 'Cost', 'Purchase Date']
['Supplier X', '001-1001', '2341', '$500.00', '1/20/14']
['Supplier X', '001-1001', '2341', '$500.00', '1/20/14']
['Supplier X', '001-1001', '5467', '$750.00', '1/20/14']
['Supplier X', '001-1001', '5467', '$750.00', '1/20/14']
['Supplier Y', '50-9501', '7009', '$250.00', '1/30/14']
['Supplier Y', '50-9501', '7009', '$250.00', '1/30/14']
['Supplier Y', '50-9505', '6650', '$125.00', '2/3/14']
['Supplier Y', '50-9505', '6650', '$125.00', '2/3/14']
['Supplier Z', '920-4803', '3321', '$615.00', '2/3/14']
['Supplier Z', '920-4805', '3321', '$615.00', '2/17/14']
['Supplier Z', '920-4804', '3321', '$6', '015.00', '2/10/14']
['Supplier Z', '920-4806', '3321', '$1', '006', '015.00', '2/24/14']

但是这本书显示了这样的预期输出:

enter image description here

我做错了什么?

最佳答案

您可以通过三种方式来更正您的输出:

  1. 从金额中删除逗号。
  2. 使用引号:将金额用双引号引起来。例如,第一行 $500.00 将是“$500.00”。引用是一种流行的技术。使用引用时,将您的阅读语句更改为:

    filereader = csv.reader(csv_input_file, delimiter=',', quotechar='"')

  3. 使用不同的分隔符。您不必使用逗号作为分隔符。要使用此方法,请将输入文件中的分隔符更改为另一个分隔符。我喜欢管道分隔的文件,因为管道很少用作文本。

    filereader = csv.reader(csv_input_file, delimiter='|')

关于python - 包含额外逗号的 csv 文件的 CSV 模块问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45777547/

相关文章:

python-2.7 - 使用 Python 将邮箱转换为 csv

javascript - 如何通过条形图的字长设置域?

python - 识别 Windows 版本

python - 如何使用 scikit-learn PCA 进行特征缩减并知道哪些特征被丢弃

bash - 如何从最后一个字段作为变量的bash调用awk

使用 XSL 转换将 XML 转换为 CSV

java - 使用 Scanner.useDelimiter ("\r\n")分隔行的 CSV 解析器不起作用

python - 是否可以从目录更改 Keras 流的类索引

python - 包含字典的类属性

python - 来自 unix utc 秒的 numpy datetime64