Python 在csv文件中打印行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40950046/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:14:27  来源:igfitidea点击:

Print rows in csv file?

pythoncsv

提问by Agent007

Here is a sample of my csv file:

这是我的 csv 文件示例:

1   Ryan    Giggs   £13.50  23  Manchester  Utd
2   David   Beckham £40.00  24  Manchester  Utd
3   Michael Owen    £22.00  22  Liverpool
4   Robbie  Fowler  £21.00  23  Leeds Utd

I have written this code with the intent to print out the first row:

我编写此代码的目的是打印出第一行:

import csv

with open("Footballers.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row[1])

However this only print out the first(technically second) column like so:

然而,这只打印出第一列(技术上第二列),如下所示:

Ryan
David
Micheal
Robbie

How can I make it print out the first row like so?

我怎样才能让它像这样打印出第一行?

1 Ryan Giggs £13.50 23 Manchester Utd

回答by Moses Koledoye

Drop the for loop and use nextif you only intend to print the first row, as the foriterates on the object and will successively supply each row:

next如果您只想打印第一行,请删除 for 循环并使用,因为for迭代对象并将连续提供每一行:

with open("Footballers.csv") as f:
    reader = csv.reader(f)
    print(next(reader)[0]) # default separator is a comma so you only get one item in the row

The readerobject is an iterator and calling nexton it will provide the nextitem which in this case is the first row. Note that this advances the iterator and subsequent iterations on it will start from the second row.

reader对象是一个迭代器,调用next它会提供一项,在这种情况下是第一行。请注意,这会推进迭代器,后续迭代将从第二行开始。

回答by Max

row[1]gives the 2nd thing in row(because it starts counting at 0). You want all of row, separated by spaces. You can replace row[1]with " ".join(row)to fix it. " "is the thing we want each item to be separated by, and rowis the list we want to separate.

row[1]给出第二个东西row(因为它从 0 开始计数)。你想要所有的row,用空格分隔。您可以替换row[1]" ".join(row)修复它。" "是我们希望每个项目被分隔的东西,row也是我们想要分隔的列表。

The full code would be

完整的代码将是

import csv

with open("Footballers.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        print(" ".join(row))

回答by SeedofWInd

Use join

使用连接

import csv

with open("Footballers.csv") as f:
   reader = csv.reader(f)
   for row in reader:
   print(' '.join(row) )