我有一个字符串,我试图写入文件,其中数据具有以下格式:
100.10 89.7 1,891.43 123.99
我希望转换为以下格式:
"100.10","89.7","1,891.43","123.99",
但是使用以下代码(其中filepath
在代码中作为文本文件位置定义,data2
是一个字符串:
csv.register_dialect('sas', delimiter=',',quoting=csv.QUOTE_ALL)
with open(filepath, "w") as f:
writer = csv.writer(f, dialect='sas')
writer.writerow(data2)
我收到了这个输出:
"1","0","0",".",1,"0","8","9",".","7","1","8","9","1",".","4","3","1","2","3",".","9","9",
我想用引号来掩盖数据中可能存在的逗号,我做错了什么?
答案 0 :(得分:2)
您正在将字符串传递给writerow
,因此它会对字符进行迭代,并在每个字符之间添加逗号。最小的修复是:
writer.writerow(data2.split(" "))
或者,将数据保存在列表中而不是首先创建字符串可能更方便!
答案 1 :(得分:2)
my_string = '100.10 89.7 1891.43 123.99'
string_list = my_string.split()
string_list返回:
['100.10', '89.7', '1891.43', '123.99']
当你这样做时:
csv.register_dialect('sas', delimiter=',',quoting=csv.QUOTE_ALL)
with open(filepath, "w") as f:
writer = csv.writer(f, dialect='sas')
writer.writerow(data2)
它按字符拆分data2,所以当你读回它时,它会将每个字符作为一个单独的列读取。你可能想要这个:
csv.register_dialect('sas', delimiter=',',quoting=csv.QUOTE_ALL)
with open(filepath, "w") as f:
writer = csv.writer(f, dialect='sas')
writer.writerow(data2.split())
修改
所以我可能会建议一个不同的方法,忘记注册一个方言,对我来说总是有问题。
string_list = ['100.10', '89.7', '1,891.43', '123.99']
with open(filepath, 'w') as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
writer.writerow(string_list)
with open(filepath, 'r') as f:
print f.read()
对我来说打印:
"100.10","89.7","1,891.43","123.99"
和
with open(filepath, 'rU') as f:
reader = csv.reader(f, quoting=csv.QUOTE_ALL)
data = next(reader) # next(reader) gives us the iterable's first row.
data
返回:
['100.10', '89.7', '1,891.43', '123.99']
所以当你写作时,请执行以下操作:
with open(filepath, "w") as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
writer.writerow(data2.split()) # *write here
您可能打算编写一堆行,因此请务必循环遍历要编写的行,或使用writerows
代替writerow
。 See the examples in the documentation.