简体   繁体   English

从 python 中的 csv 行创建列表

[英]Create list from csv lines in python

I have a csv file with 2 rows and multiple lines.我有一个包含 2 行和多行的 csv 文件。

import csv

with open('data.csv', 'r') as csv_file:
     csv_reader = csv.reader(csv_file)

     next(csv_reader)

     for row in csv_reader:
         print(row[0])

The output is: output 是:

row0line0
row0line1
row0line2
...

Is there a way i could further separate the rows into a list of individual cells?有没有办法可以进一步将行分成单个单元格的列表? Thanks谢谢

As I understand your csv file look like this:据我了解,您的 csv 文件如下所示:

row0line0
row1line1
...

If its possible i should reccomand to change it to:如果可能的话,我应该建议将其更改为:

row0 line0
row1 line1
...

(Add a space between the rows and the lines) (在行和行之间添加一个空格)

Then you can update your code to the code bellow to print only the rows and create two lists - one that contain the rows and another that contain the lines:然后,您可以将代码更新为下面的代码以仅打印行并创建两个列表 - 一个包含行,另一个包含行:

import csv

with open('data.csv', 'r') as csv_file:

csv_reader = csv.reader(csv_file)

next(csv_reader)
rows = []
lines = []
for item in csv_reader:
    temp = item[0].split(" ")
    rows.append(temp[0])
    lines.append(temp[1])
    print(temp[0])

If you mean that each row becomes an element of the list that goes this way:如果您的意思是每一行都成为这样的列表的一个元素:

with open('data.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    data_list = [row[0] for row in reader]

Otherwise, if you want to create a list of the first elements of each line, you can do this:否则,如果要创建每行的第一个元素的列表,可以这样做:

with open('data.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    row0_list = []
    for row in reader:
      row0_list.append(row[0])

I hope the problem is solved with this explanation.我希望通过这个解释解决问题。

My understanding is that you are asking to output all the data fields.我的理解是您要求 output 所有数据字段。 csv_reader is already separating your rows into a list individual cells! csv_reader 已经将您的行分成单个单元格列表!

You current script reads the file one line at a time and prints the first item in each row with this line:您当前的脚本一次读取一行文件,并使用此行打印每行中的第一项:

    for row in csv_reader:
        print(row[0])

Instead of printing row[0], which only prints the first field in the csv row, you can just print the row:而不是打印行 [0],它只打印 csv 行中的第一个字段,您可以只打印该行:

    for row in csv_reader:
        print(row)

That will output the field lists (from my sample csv):这将 output 字段列表(来自我的示例 csv):

['r0v0', 'r0v1', 'r0v2']
['r1v0', 'r1v1', 'r1v2']

If you want to print in a nicer format, you can use join:如果您想以更好的格式打印,可以使用 join:

    for row in csv_reader:
        print(", ".join(row))

Output: Output:

r0v0, r0v1, r0v2
r1v0, r1v1, r1v2

My csv:我的 csv:

r0v0,r0v1,r0v2
r1v0,r1v1,r1v2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM