[英]Printing .csv file as list in python
My Code: 我的代码:
import csv
with open('serialnumber.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
your_list = list(reader)
print(your_list)
.csv file: .csv文件:
hello,bye
Printed output : 打印输出:
[['hello', 'bye']]
I need to get list like this : 我需要这样的清单:
['hello', 'bye']
What I'm doing wrong? 我做错了什么?
The reason you are getting [["hello", "bye"]]
is because, if the CSV has multiple lines, they will be items inside the first list. 您收到[["hello", "bye"]]
的原因是,如果CSV有多行,它们将成为第一个列表中的项目。
You can get what you want by accessing the first item of your_list
like this: 您可以通过访问your_list
的第一项来获得所需的your_list
如下所示:
>>> print(your_list[0])
["hello", "bye"]
There is no problem with your code. 您的代码没有问题。 It is just that you are making a list out of all rows of the csv. 只是您要在csv的所有行中列出一个列表。 That is why you are getting a list of lists. 这就是为什么要获取列表列表的原因。 To get each row as a list you can simply iterate over the reader and you will get a list for each row. 要将每一行作为列表,您可以简单地遍历阅读器,然后将获得每一行的列表。 This technique is particularly useful when you have a large file. 当您有大文件时,此技术特别有用。
import csv
with open('serialnumber.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
for r in reader:
print r
You can see a two-dimensional array of CSV file [print(r) for r in your_list]
您可以[print(r) for r in your_list]
看到CSV文件的二维数组[print(r) for r in your_list]
import csv
with open('serialnumber.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
your_list = list(reader)
#print(your_list)
[print(r) for r in your_list]
If you want to flatten the whole csv reader i would use list comprehenstion
如果您想弄平整个csv阅读器,我会使用list comprehenstion
import csv
with open('serialnumber.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
_list = [word for _iter in reader for word in _iter]
print(_list)
You could also use sum
: 您也可以使用sum
:
_list = sum(reader, [])
Example one row csv : 示例一行csv :
hello,bye
Output: 输出:
['hello', 'bye']
Example multi-row csv : 多行csv示例:
hello,bye,bye
bye,bye,hello
bye,hello,bye
Output: 输出:
['hello', 'bye', 'bye', 'bye', 'bye', 'hello', 'bye', 'hello', 'bye']
If your csv file has just one row you could use plain print
: 如果您的csv文件只有一行,则可以使用普通print
:
import csv
with open('serialnumber.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
print(*reader)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.