Python strip every double quote from csv

2019-07-21 18:27发布

Hi I have a csv file that looks like the following.

"AB" ; "AA" ; "BA" ; "HI"
"CD" ; "BB" ; "BC" ; "JK"
"EF" ; "CC" ; "CE" ; "LM"
"GH" ; "DD" ; "DG" ; "MN"

How can I get the following code to strip off all the double quotes from every column in a csv file as for now it strips only the first column. Thanks

import csv

f = open("wakhawakha.csv", 'rt')
try:
    for row in csv.reader(f, delimiter=' ', skipinitialspace=True):
        print('|'.join(row))
finally:
        f.close()

3条回答
干净又极端
2楼-- · 2019-07-21 19:12

Open it and read the string first.

import csv

with open("wakhawakha.csv", 'rt') as f:
    data = f.read()
new_data = data.replace('"', '')
for row in csv.reader(new_data.splitlines(), delimiter=' ', skipinitialspace=True):
    print ('|'.join(row))
查看更多
小情绪 Triste *
3楼-- · 2019-07-21 19:14

Is this what you wanted?

    for row in csv.reader(f, delimiter=';', skipinitialspace=True):
        print (''.join(row))
查看更多
劳资没心,怎么记你
4楼-- · 2019-07-21 19:27

EDIT I noticed you changed your indentation. The indentation in your OP was wrong: Now it's fine:

f = open("wakhawakha.csv", 'rt')
try:
    for row in csv.reader(f, delimiter=' ', skipinitialspace=True):
        print ('|'.join(row))
finally:
    f.close()

This way the output is this:

AB|;|AA|;|BA|;|HI
CD|;|BB|;|BC|;|JK
EF|;|CC|;|CE|;|LM
GH|;|DD|;|DG|;|MN

Is this the output you wanted? Or, did you just want to strip off all the double quotes? If so, then change this line in your code:

print ('|'.join(row))

to this:

print (' '.join(row))

Then you will get this output:

AB ; AA ; BA ; HI
CD ; BB ; BC ; JK
EF ; CC ; CE ; LM
GH ; DD ; DG ; MN
查看更多
登录 后发表回答