如何获取 csv 文件的特定字段?

发布于 2024-11-03 04:52:52 字数 513 浏览 0 评论 0原文

我需要一种方法来获取 CSV 的特定项目(字段)。假设我有一个包含 100 行和 2 列(逗号分隔)的 CSV。第一列电子邮件,第二列密码。例如,我想获取第 38 行中电子邮件的密码。所以我只需要第二列第 38 行中的项目...

假设我有一个 csv 文件:

[email protected],bbbbb
[email protected],ddddd

例如,如何仅获取“ddddd”?

我是这门语言的新手,尝试了 csv 模块的一些东西,但我不明白......

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...

Say I have a csv file:

[email protected],bbbbb
[email protected],ddddd

How can I get only 'ddddd' for example?

I'm new to the language and tried some stuff with the csv module, but I don't get it...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

人心善变 2024-11-10 04:52:52
import csv
mycsv = csv.reader(open(myfilepath))
for row in mycsv:
   text = row[1]

按照此处对SO问题的评论,最好的,更强大的代码是:

import csv
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    for row in mycsv:
        text = row[1]
        ............

更新:如果OP实际想要的是csv文件最后一行中的最后一个字符串,则有几种不一定需要的方法csv。例如,

fulltxt = open(mifilepath, 'rb').read()
laststring = fulltxt.split(',')[-1]

这对于非常大的文件来说并不好,因为您将完整的文本加载到内存中,但对于小文件来说可能没问题。请注意,laststring 可能包含换行符,因此在使用前将其删除。

最后,如果 OP 想要的是第 n 行中的第二个字符串(对于 n=2):

更新 2: 现在,这与 JFSebastian 的答案中的代码相同。 (功劳归于他):

import csv
line_number = 2     
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    mycsv = list(mycsv)
    text = mycsv[line_number][1]
    ............
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]
        ............

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]

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.

And finally if what the OP wants is the second string in line n (for n=2):

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]
    ............
屋檐 2024-11-10 04:52:52
#!/usr/bin/env python
"""Print a field specified by row, column numbers from given csv file.

USAGE:
    %prog csv_filename row_number column_number
"""
import csv
import sys

filename = sys.argv[1]
row_number, column_number = [int(arg, 10)-1 for arg in sys.argv[2:])]

with open(filename, 'rb') as f:
     rows = list(csv.reader(f))
     print rows[row_number][column_number]

示例

$ python print-csv-field.py input.csv 2 2
ddddd

注意:list(csv.reader(f)) 将整个文件加载到内存中。为了避免这种情况,您可以使用itertools:

import itertools
# ...
with open(filename, 'rb') as f:
     row = next(itertools.islice(csv.reader(f), row_number, row_number+1))
     print row[column_number]
#!/usr/bin/env python
"""Print a field specified by row, column numbers from given csv file.

USAGE:
    %prog csv_filename row_number column_number
"""
import csv
import sys

filename = sys.argv[1]
row_number, column_number = [int(arg, 10)-1 for arg in sys.argv[2:])]

with open(filename, 'rb') as f:
     rows = list(csv.reader(f))
     print rows[row_number][column_number]

Example

$ python print-csv-field.py input.csv 2 2
ddddd

Note: list(csv.reader(f)) loads the whole file in memory. To avoid that you could use itertools:

import itertools
# ...
with open(filename, 'rb') as f:
     row = next(itertools.islice(csv.reader(f), row_number, row_number+1))
     print row[column_number]
等风也等你 2024-11-10 04:52:52
import csv

def read_cell(x, y):
    with open('file.csv', 'r') as f:
        reader = csv.reader(f)
        y_count = 0
        for n in reader:
            if y_count == y:
                cell = n[x]
                return cell
            y_count += 1

print (read_cell(4, 8)) 

此示例在 Python 3 中打印单元格 4、8。

import csv

def read_cell(x, y):
    with open('file.csv', 'r') as f:
        reader = csv.reader(f)
        y_count = 0
        for n in reader:
            if y_count == y:
                cell = n[x]
                return cell
            y_count += 1

print (read_cell(4, 8)) 

This example prints cell 4, 8 in Python 3.

秋叶绚丽 2024-11-10 04:52:52

关于 csv.reader() 对象,您需要了解一个有趣的点。 csv.reader 对象不是 list 类型,并且不可下标。

这是可行的:

for r in csv.reader(file_obj): # file not closed
    print r

这不行:

r = csv.reader(file_obj) 
print r[0]

因此,您首先必须转换为列表类型才能使上述代码工作。

r = list( csv.reader(file_obj) )
print r[0]          

There is an interesting point you need to catch about csv.reader() object. The csv.reader object is not list type, and not subscriptable.

This works:

for r in csv.reader(file_obj): # file not closed
    print r

This does not:

r = csv.reader(file_obj) 
print r[0]

So, you first have to convert to list type in order to make the above code work.

r = list( csv.reader(file_obj) )
print r[0]          
傲影 2024-11-10 04:52:52

以下可能就是您正在寻找的内容:

import pandas as pd

df = pd.read_csv("table.csv")

print(df["Password"][row_number])  

#where row_number is 38 maybe

Following may be be what you are looking for:

import pandas as pd

df = pd.read_csv("table.csv")

print(df["Password"][row_number])  

#where row_number is 38 maybe
深海蓝天 2024-11-10 04:52:52

终于我明白了!!!

import csv

def select_index(index):
    csv_file = open('oscar_age_female.csv', 'r')
    csv_reader = csv.DictReader(csv_file)

    for line in csv_reader:
        l = line['Index']
        if l == index:
            print(line[' "Name"'])

select_index('11')

<块引用>
<块引用>

“贝蒂·戴维斯”


Finaly I got it!!!

import csv

def select_index(index):
    csv_file = open('oscar_age_female.csv', 'r')
    csv_reader = csv.DictReader(csv_file)

    for line in csv_reader:
        l = line['Index']
        if l == index:
            print(line[' "Name"'])

select_index('11')

"Bette Davis"

回心转意 2024-11-10 04:52:52
import csv
inf = csv.reader(open('yourfile.csv','r'))
for row in inf:
  print row[1]
import csv
inf = csv.reader(open('yourfile.csv','r'))
for row in inf:
  print row[1]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文