Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3-将包含整数元组的列表写入CSV_Python_Python 3.x_Csv - Fatal编程技术网

Python3-将包含整数元组的列表写入CSV

Python3-将包含整数元组的列表写入CSV,python,python-3.x,csv,Python,Python 3.x,Csv,好的,我有一个程序,输出包含整数的元组,并将它们附加到如下列表中: [(0,98,7), (437, 563, 128), (82, 45, 221)...] 0,98,7 437, 563, 128 82, 45, 221 ... 我想用.write()函数将元组写入一个文件,如下面所示,元组存储在“值”列表中: output=open("output.txt","w") for v in range(len(values)): print(values[v]) #so it pr

好的,我有一个程序,输出包含整数的元组,并将它们附加到如下列表中:

[(0,98,7), (437, 563, 128), (82, 45, 221)...]
0,98,7
437, 563, 128
82, 45, 221
...
我想用.write()函数将元组写入一个文件,如下面所示,元组存储在“值”列表中:

output=open("output.txt","w")
for v in range(len(values)):
    print(values[v]) #so it prints each value in the shell for error check
    output.write(values[v])
预期结果是一个文本文件,其内容如下:

[(0,98,7), (437, 563, 128), (82, 45, 221)...]
0,98,7
437, 563, 128
82, 45, 221
...
问题是它说它不能将元组写入文件;它需要一个字符串。我尝试使用.join()函数和list()函数将元组更改为字符串或值列表中的列表。有人知道我如何解决这个问题吗?非常感谢。

这正是模块的用途:

import csv

with open('output.txt','w',newline='') as fou:
  cw = csv.writer(fou)
  cw.writerows(values)

鉴于有些人已经展示了
csv
方式,这里没有

s = [(0,98,7), (437, 563, 128), (82, 45, 221)]
with open('out.txt', 'w') as f:
    for e in s:
        f.write('%s\n' % ','.join(str(n) for n in e))
把它们写成一个循环。传递给join的集合中的每个元素都应该是字符串,因此请转换每个值,然后使用join使逗号分隔行

结果

ubuntu@ubuntu:~$ cat out.txt
0,98,7
437,563,128
82,45,221

请注意,输出中逗号后不总是有空格。如果没有他们,我会像第一行一样离开。如果您想让他们更改您的连接字符串,'.join(等)=>
','.join(等)

您在
join
中使用的代码是什么?阻止它工作的错误是什么?此外,请考虑使用<代码>打开(‘输出.txt’,w’)作为OutPuxField:……/Cult>,这是更安全的,因为即使存在错误也会关闭文件。对值中的v使用
。2.可能这是
output.write(str(v))
。3.别忘了(在最后)关闭文件。感谢所有在这方面帮助我的人;我猜我找错了地方,得到了错误的答案……我对python比较熟悉,从来没有读过CSV模块。非常感谢;这些信息非常有用!对!<代码>,。连接(字符串)不是CSV,滚动您自己的序列化程序/解析器是一个糟糕的主意。使用该模块。谢谢@DSM。更新答案。@Bernie非常感谢您!!!你们两个@钻石心:不客气:-)