如何使用Python从CSV文件中删除空的双引号?
这是文件的当前外观:
"text","more text","","other text","","text"
这是我想要的样子:
"text","more text",,"other text",,"text"
答案 0 :(得分:0)
我认为最好的解决方案是使用csv.reader
中的quotechar
选项,然后过滤空白字段:
import csv
with open('test.csv', newline='') as csvf:
for row in csv.reader(csvf, delimiter=',', quotechar='"'):
row = filter(lambda v: v, row)
# Now row is just an iterator containing non-empty strings
# You can use it as you please, for example:
print(', '.join(row))
如果不是要删除空字段,您需要将它们替换为给定值(例如None
):
import csv
def read(file, placeholder=None):
with open(file, newline='') as csvf:
for row in csv.reader(csvf, delimiter=',', quotechar='"'):
yield [v if v else placeholder for v in row]
for row in read('test.csv'):
pass # Do something with row
例如,如果您需要使用双引号将其打印到标准输出(这是一个愚蠢的示例):
for row in read('test.csv'):
print(', '.join(f'"{v}"' if v else '' for v in row))
答案 1 :(得分:0)
您可以尝试:
>>> s=""""text","more text","","other text","","text" """
>>> s
'"text","more text","","other text","","text" '
>>> s.replace('""','')
'"text","more text",,"other text",,"text" '
答案 2 :(得分:0)