Python 如何仅读取 CSV 文件每一行的第一列

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

How to read just the first column of each row of a CSV file

pythoncsv

提问by Luca23

How to read just the first column of each row of a CSV file in Python?

如何在 Python 中仅读取 CSV 文件每一行的第一列?

My data is something like this:

我的数据是这样的:

1 abc    
2 bcd    
3 cde

and I only need to loop trough the values of the first column.

我只需要遍历第一列的值。

Also, when I open the csv File in calc the data in each row is all in the same cell, is that normal?

另外,当我在 calc 中打开 csv 文件时,每行中的数据都在同一个单元格中,这正常吗?

回答by Avinash Raj

import csv
with open(file) as f:
    reader = csv.reader(f, delimiter="\t")
    for i in reader:
        print i[0]

OR

或者

change the delimter to space if necessary.

如有必要,将分隔符更改为空格。

reader = csv.reader(f, delimiter=" ")

without csv module,

没有 csv 模块,

import csv
with open(file) as f:
    for line in f:
        print line.split()[0]

回答by Kasramvd

You can use itertools.izipto crate a generator contains the columns and use nextto get the first column.Its more efficient if you have a large data and you want to refuse of multi-time indexing!

您可以使用itertools.izipcrate 生成包含列的生成器并用于next获取第一列。如果您有大量数据并且您想拒绝多次索引,则效率更高!

import csv
from itertools import izip
with open('ex.csv', 'rb') as csvfile:
     spamreader = csv.reader(csvfile, delimiter=' ')
     print next(izip(*spamreader))

回答by leekaiinthesky

To get just the first column as a list:

将第一列作为列表获取:

with open('myFile.csv') as f:
    firstColumn = [line.split(',')[0] for line in f]

回答by yoook

for the second part of your question:

对于您问题的第二部分:

when opening csv-documents in LibreOffice Calc (openoffice should work the same way) I get a Dialog where I am asked a few things about that document, like charakter encoding and as well the type of separator. If you select "space", it should work. You have a preview at the bottom of this dialog.

在 LibreOffice Calc 中打开 csv 文档时(openoffice 应该以相同的方式工作)我得到一个对话框,在那里我被问到关于该文档的一些事情,比如字符编码以及分隔符的类型。如果您选择“空间”,它应该可以工作。您可以在此对话框底部进行预览。