如何管理读取csv的问题,这是一个以分号分隔的文件,其中一些字符串包含分号?

TJE*_*TJE 1 python csv string

我可以通过在我的csv(以分号分隔)文件中显示几个示例行来说明我遇到的问题,如下所示:

4;1;"COFFEE; COMPANY";4
3;2;SALVATION ARMY;4
Run Code Online (Sandbox Code Playgroud)

请注意,在一行中,一个字符串在引号中并且在其中有一个分号(除了包含分号的列之外,没有列在我的输入文件中有引号).

带引号和分号的这些行导致了问题 - 基本上,我的代码在列/字段内的引号内计算分号.因此,当我在这一行中读取时,它会在字符串中读取这个分号作为分隔符,从而使得该行看起来像是一个额外的字段/列.

所需的输出看起来像这样,"咖啡公司"周围没有引号,"咖啡"和"公司"之间没有分号:

4;1;COFFEE COMPANY;4
3;2;SALVATION ARMY;4
Run Code Online (Sandbox Code Playgroud)

实际上,这个带有"咖啡公司"的专栏对我来说完全没用,所以最终文件也可能是这样的:

4;1;xxxxxxxxxxx;4
3;2;xxxxxxxxxxx;4
Run Code Online (Sandbox Code Playgroud)

我怎样才能摆脱这个特定列中的半冒号,但是没有摆脱所有其他的冒号?

mar*_*eau 7

csv模块可以轻松处理这样的工作:

# Contents of input_file.csv
# 4;1;"COFFEE; COMPANY";4
# 3;2;SALVATION ARMY;4

import csv
input_file = 'input_file.csv'  # Contents as shown in your question.

with open(input_file, 'r', newline='') as inp:
    for row in csv.reader(inp, delimiter=';'):
        row[2] = row[2].replace(';', '')  # Removed embedded ';' chars.
        # If you don't care about what's in the column, use the following instead:
        # row[2] = 'xxxxxxxxxxx'  # Value not needed.
        print(';'.join(row))
Run Code Online (Sandbox Code Playgroud)

印刷输出:

4;1;COFFEE COMPANY;4
3;2;SALVATION ARMY;4
Run Code Online (Sandbox Code Playgroud)

后续问题:如何将此数据写入新的csv文件?

import csv
input_file = 'input_file.csv'  # Contents as shown in your question.
output_file = 'output_file.csv'

with open(input_file, 'r', newline='') as inp, \
     open(output_file, 'w', newline='') as outp:
    writer= csv.writer(outp, delimiter=';')
    for row in csv.reader(inp, delimiter=';'):
        row[2] = row[2].replace(';', '')  # Removed embedded ';' chars.
        writer.writerow(row)
Run Code Online (Sandbox Code Playgroud)