我有一个列表,其内容必须写入csv文件,不带引号。
列表内容如下所示:
list=[(1, 2, 1), (1, 3, 1), (1, 4, 1), (1, 5, 1), (2, 1, 1), (2, 3, 1), (2, 4, 1), (2, 5, 1), (3, 1, 1), (3, 2, 1), (3, 4, 1), (3, 5, 1), (4, 1, 1), (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 1, 1), (5, 2, 1), (5, 3, 1), (5, 4, 1)]
现在我有以下两个代码片段,它试图将此列表写入csv文件:
方法1:
def method1():
list=[(1, 2, 1), (1, 3, 1), (1, 4, 1), (1, 5, 1), (2, 1, 1), (2, 3, 1), (2, 4, 1), (2, 5, 1), (3, 1, 1), (3, 2, 1), (3, 4, 1), (3, 5, 1), (4, 1, 1), (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 1, 1), (5, 2, 1), (5, 3, 1), (5, 4, 1)]
myfile = open('output.csv', 'w')
wr = csv.writer(myfile, quoting = csv.QUOTE_NONE, delimiter=',', escapechar=',')
wr.writerow(list)
csv文件的内容如下所示:
(1,, 2,, 1),(1,, 3,, 1),(1,, 4,, 1),(1,, 5,, 1),(2,, 1,, 1),(2,, 3,, 1),(2,, 4,, 1),(2,, 5,, 1),(3,, 1,, 1),(3,, 2,, 1),(3,, 4,, 1),(3,, 5,, 1),(4,, 1,, 1),(4,, 2,, 1),(4,, 3,, 1),(4,, 5,, 1),(5,, 1,, 1),(5,, 2,, 1),(5,, 3,, 1),(5,, 4,, 1)
我不想要","在列表的元素之间。如果我从上面的代码中删除escapechar,它会抛出一个错误。
错误是:
_csv.Error:需要转义,但没有设置escapechar
方法2:
def method2():
list=[(1, 2, 1), (1, 3, 1), (1, 4, 1), (1, 5, 1), (2, 1, 1), (2, 3, 1), (2, 4, 1), (2, 5, 1), (3, 1, 1), (3, 2, 1), (3, 4, 1), (3, 5, 1), (4, 1, 1), (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 1, 1), (5, 2, 1), (5, 3, 1), (5, 4, 1)]
myfile = open('output.csv', 'wb')
wr = csv.writer(myfile)
wr.writerow(list)
方法2的输出如下所示:
"(1,2,1)","(1,3,1)","(1,4,1)" ,"(1,5,1)","(2,1,1)","(2,3,1)",& #34;(2,4,1)","(2,5,1)","(3,1,1)",&#34 ;(3,2,1)","(3,4,1)","(3,5,1)","( 4,1,1)","(4,2,1)","(4,3,1)","(4, 5,1)","(5,1,1)","(5,2,1)","(5,3, 1)","(5,4,1)"
有人可以帮我解决这个问题吗?
我的输出文件的内容必须如下所示:
(1, 2, 1),
(1, 3, 1),
(1, 4, 1),
(1, 5, 1),
...
...
答案 0 :(得分:2)
你根本不需要csv,看看这个:
>>> list=[(1, 2, 1), (1, 3, 1), (1, 4, 1), (1, 5, 1), (2, 1, 1), (2, 3, 1), (2, 4, 1), (2, 5, 1), (3, 1, 1), (3, 2, 1), (3, 4, 1), (3, 5, 1), (4, 1, 1), (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 1, 1), (5, 2, 1), (5, 3, 1), (5, 4, 1)]
>>> with open('out.txt', 'w') as out:
... for t in list:
... out.write(str(t)+",\n")
...
>>>
host:~$ head out.txt
(1, 2, 1),
(1, 3, 1),
(1, 4, 1),
(1, 5, 1),
(2, 1, 1),
(2, 3, 1),
(2, 4, 1),
(2, 5, 1),
(3, 1, 1),
(3, 2, 1),
答案 1 :(得分:2)
您描述的格式似乎不需要csv
模块。您可以使用以下内容写出格式:
list=[(1, 2, 1), (1, 3, 1), (1, 4, 1), (1, 5, 1), (2, 1, 1), (2, 3, 1), (2, 4, 1), (2, 5, 1), (3, 1, 1), (3, 2, 1), (3, 4, 1), (3, 5, 1), (4, 1, 1), (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 1, 1), (5, 2, 1), (5, 3, 1), (5, 4, 1)]
with open("output.csv", "w") as out_f:
for item in list:
output_str = "{},\n".format(item)
out_f.write(output_str)