【发布时间】:2018-01-25 13:30:56
【问题描述】:
我遇到了一个独特的问题。 我有代码:
with open("test.csv", "r") as csvFile:
reader = csv.reader(csvFile, skipinitialspace=True)
for row in reader:
for obj in row:
print(obj)
示例 csv 文件:
anotherCommand, e=5, f=6, g=7, h=9, test="aaa, bbb, ggggg"
我想用这种方式分割这个字符串:
anotherCommand
e=5
f=6
g=7
h=9
test="aaa, bbb, ggggg"
但是我呈现的代码以这种方式拆分这些字符串:
anotherCommand
e=5
f=6
g=7
h=9
test="aaa
bbb
ggggg"
这是错误的解决这个问题。 我看到了这样的话题: Why is the Python CSV reader ignoring double-quoted fields? 要么 How can i parse a comma delimited string into a list (caveat)?
但是这个例子是不同的,这些例子没有出乎我的意料。 有人有想法吗?
【问题讨论】:
-
@cᴏʟᴅsᴘᴇᴇᴅ 不起作用,与链接网站中的情况相同:)
-
你能补充一些细节吗?你到底做了什么,没用。
-
我写道:with open("test.csv", "r") as csvFile: for line in csv.reader(csvFile, quotechar='"', delimiter=',', quoting= csv.QUOTE_ALL, skipinitialspace=True): print(len(line)) ---- 我仍然得到与我的主要答案中相同的值
-
我将我的代码建模为您链接的答案:)
-
问题的关键是您的“csv”不是格式正确的 CSV 文件。如果您可以生成它使其有效,那么 python csv 解析将起作用。对于您的示例,您似乎需要在 test="aaa, bbb, ggggg" 周围添加引号,因此它看起来像“test="aaa, bbb, ggggg"”,但您可能只需在每个值周围添加引号即可。