【发布时间】:2017-06-16 14:11:27
【问题描述】:
我有一个逗号分隔的文件(来自第三方),其中每行以空格开头和结尾,字段用双引号引起来,文件以只有空格的行结尾。
"first_name";"last_name"
"John";"Doe"
"Anita";"Doe"
我尝试使用以下代码阅读此内容。
import csv
import json
def read_csv(filename):
result = []
with open(filename, 'r', encoding='utf-8') as f:
csv_reader = csv.reader(f, delimiter=';', quotechar='"')
for line_index, line in enumerate(csv_reader):
if line_index == 0:
header = line
continue
result.append(dict(zip(header, line)))
return result
if __name__ == '__main__':
contents = read_csv('test.txt')
print(json.dumps(contents, indent=4, sort_keys=4))
这是我的预期结果:
[
{
"first_name": "John",
"last_name ": "Doe "
},
{
"first_name": "Anita",
"last_name ": "Doe "
}
]
但是,由于前导空格,它总是将双引号作为第一列的一部分,而且它还考虑了最后一行。这是我得到的结果:
[
{
" \"first_name\"": " \"John\"",
"last_name ": "Doe "
},
{
" \"first_name\"": " \"Anita\"",
"last_name ": "Doe "
},
{
" \"first_name\"": " "
}
]
如何在解析 csv 之前 去除这些前导和尾随空格?答案here 展示了如何在读取字段后从字段中删除空格,但这在这里并不好,因为我要更改的不是字段的内容,而是字段本身。
顺便说一句:我使用的是 Python 3.5。
编辑
我现在使用以下代码跳过空行:
# Skip empty lines
line = [column.strip() for column in line]
if not any(line):
continue
【问题讨论】:
标签: python csv whitespace