Python 将二维数组写入带有分隔符的 csv 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44691524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write a 2d array to a csv file with delimiter
提问by JefferyLR
As the title says, I want to write a 2D array to a csv file with delimiter ',' using python. My array looks like this (ndarray):
正如标题所说,我想使用 python 将一个二维数组写入一个带有分隔符 ',' 的 csv 文件。我的数组看起来像这样(ndarray):
a= [[1,2,3,4],[5,6,7,8]]
and I want the output to look like:
我希望输出看起来像:
1,2,3,4
5,6,7,8
with open('./data/positive.csv','wb') as myfile:
wr = csv.writer(myfile) #, quoting=csv.QUOTE_ALL)
wr.writerow(a)
How do I accomplish this?
我该如何实现?
I already have tried the solution but it doesn't work since I misplaced an 's' in my 'row' and it makes my array write to a single row instead of multiple rows.
我已经尝试过该解决方案,但它不起作用,因为我在“行”中放错了一个“s”,它使我的数组写入单行而不是多行。
回答by void
Use csv
module by import csv
also take a note you might need either writerow()
or writerows()
.
使用csv
module byimport csv
还请记下您可能需要writerow()
或writerows()
。
What's the difference you may ask?
你可能会问有什么区别?
writerow takes an iterable of cells to write:
writerow 需要一个可迭代的单元格来写入:
writerow([1,2,2])
->
1,2,2
writerows takes an iterable of iterables of cells to write:
writerows 需要一个可迭代的单元格来写入:
writerows([[1,2,3],
[4,5,6],
[6,7,8]])
->
1,2,3
4,5,6
6,7,8
Which can be ofcourse be given as a variable. Like
这当然可以作为变量给出。喜欢
a = [[1,2,3],[4,5,6],[6,7,8]]
writerows(a)
Conclusion writerow takes 1-dimensional data (one row), and writerows takes 2-dimensional data (multiple rows).
结论 writerow 取一维数据(一行),而 writerows 取二维数据(多行)。
Program for you:
为您计划:
import csv
a = [[1,2,3,4],[5,6,7,8]]
with open("new_file.csv","w+") as my_csv:
csvWriter = csv.writer(my_csv,delimiter=',')
csvWriter.writerows(a)
Note open()
takes two arguments here the file to be written and the mode.
注意open()
这里有两个参数要写入的文件和模式。
What is a mode you may ask?
你可能会问什么是模式?
It specifies how the file should be opened. In my case w+
means open file my_file.csv
if it exists if it doesn't then fine create a new one and write.
它指定文件的打开方式。在我的情况下w+
意味着打开文件my_file.csv
,如果它不存在,则可以创建一个新文件并写入。
There are several modes choose one. Note: w+
overwrites everytime you use it. That is old data in file will be overwritten so if you want to just append use a
. Take a look at this for more details on modes.File modes
有多种模式选择一种。注意:w+
每次使用时都会覆盖。那是文件中的旧数据将被覆盖,因此如果您只想附加 use a
。有关模式的更多详细信息,请查看此内容。文件模式
回答by Rudresh Panchal
Assuming that a is a numpy array,
假设 a 是一个 numpy 数组,
import numpy
a= [[1,2,3,4],[5,6,7,8]]
numpy.savetxt('output.csv',a,delimiter=",")
回答by moritzg
Python's built in csv
module does this easily:
Python 的内置csv
模块很容易做到这一点:
import csv
a= [[1,2,3,4],[5,6,7,8]]
with open("output.csv", "w") as f:
writer = csv.writer(f)
writer.writerows(a)
回答by Wasi Ahmad
A simple way to achieve this is as follows.
实现此目的的简单方法如下。
a= [[1,2,3,4],[5,6,7,8]]
f = open('file.csv', 'w')
for item in a:
for i in range(len(item)):
if i == 0:
f.write(str(item[i]))
else:
f.write(',' + str(item[i]))
f.write('\n')
f.close()
Another alternative:
另一种选择:
a= [[1,2,3,4],[5,6,7,8]]
f = open('file.csv', 'w')
for item in a:
f.write(','.join([str(x) for x in item]) + '\n')
f.close()
Edit: Please note, use of csv
module to write in csv files is always preferred. The solution I have suggested is more generic and can be useful to write things in any format in any type of file.
编辑:请注意,csv
始终首选使用模块写入 csv 文件。我建议的解决方案更通用,可用于在任何类型的文件中以任何格式编写内容。
回答by voidpro
You can create a file object and print to a file, as below.
您可以创建文件对象并打印到文件,如下所示。
f=open('file.csv','w')
a= [[1,2,3,4],[5,6,7,8]]
for x in a:
print(",".join([str(i) for i in x]), file=f)
f.close()
回答by Shahbaaz
Python has a built in CSV module which can be used to read and write CSV's.
Python 有一个内置的 CSV 模块,可用于读取和写入 CSV。
import csv
a= [[1,2,3,4],[5,6,7,8]]
with.open("myFile.csv", "w+") as myCsv:
csvWriter = csv.writer(myCsv, delimiter=',')
csvWriter.writerows(a)
You can read documentation on CSV module using Thislink.
您可以使用此链接阅读有关 CSV 模块的文档。
EDIT: changed writeRow to writerows also removed wb and w+. Thanks @s_vishnu for pointing out the mistakes.
编辑:将 writeRow 更改为 writerows 也删除了 wb 和 w+。感谢@s_vishnu 指出错误。