如何获取CSV文件的特定字段? [英] How can I get a specific field of a csv file?
问题描述
我需要一种获取CSV特定项目(字段)的方法.假设我有一个包含100行和2列的CSV(逗号分隔).第一栏电子邮件,第二栏密码.例如,我想在第38行中获取电子邮件的密码.因此,我只需要第二列第38行中的项目...
I need a way to get a specific item(field) of a CSV. Say I have a CSV with 100 rows and 2 columns (comma seperated). First column emails, second column passwords. For example I want to get the password of the email in row 38. So I need only the item from 2nd column row 38...
说我有一个csv文件:
Say I have a csv file:
aaaaa@aaa.com,bbbbb
ccccc@ccc.com,ddddd
例如,如何仅获得"ddddd"?
How can I get only 'ddddd' for example?
我是该语言的新手,尝试使用csv模块进行一些操作,但我不明白...
I'm new to the language and tried some stuff with the csv module, but I don't get it...
推荐答案
import csv
mycsv = csv.reader(open(myfilepath))
for row in mycsv:
text = row[1]
在此处的注释之后,最好的,更健壮的代码是:
Following the comments to the SO question here, a best, more robust code would be:
import csv
with open(myfilepath, 'rb') as f:
mycsv = csv.reader(f)
for row in mycsv:
text = row[1]
............
更新:如果OP真正想要的是csv文件最后一行中的最后一个字符串,则有一些方法不一定需要csv.例如,
Update: If what the OP actually wants is the last string in the last row of the csv file, there are several aproaches that not necesarily needs csv. For example,
fulltxt = open(mifilepath, 'rb').read()
laststring = fulltxt.split(',')[-1]
这不适用于大文件,因为您可以将完整的文本加载到内存中,但对于小文件则可以.请注意,laststring
可能包含换行符,因此请在使用前将其删除.
This is not good for very big files because you load the complete text in memory but could be ok for small files. Note that laststring
could include a newline character so strip it before use.
最后,如果OP想要的是第n行中的第二个字符串(对于n = 2):
And finally if what the OP wants is the second string in line n (for n=2):
更新2:现在,此代码与J.F. Sebastian回答中的代码相同. (功劳是他的):
Update 2: This is now the same code than the one in the answer from J.F.Sebastian. (The credit is for him):
import csv
line_number = 2
with open(myfilepath, 'rb') as f:
mycsv = csv.reader(f)
mycsv = list(mycsv)
text = mycsv[line_number][1]
............
这篇关于如何获取CSV文件的特定字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!