使用 Python DictReader 获取特定行和值

发布于 2024-10-15 23:19:56 字数 264 浏览 1 评论 0原文

我有一个 csv 文件,并试图在第 20 行第 3 列上获取一个特定值。

但到目前为止,我所做的只是在第 3 列上显示所有值(此处称为“名称”) ”)。

这是我的 Python 代码

d = DictReader(r.csv().split('\n'))
for line in d:
    score = line["name"]
    print score

如何仅显示和获取特定行的值?

I have a csv file and am trying to get one specific value on, say, line 20, column 3.

But so far, all I managed is to display all values on column 3 (here called "name").

Here is my Python code

d = DictReader(r.csv().split('\n'))
for line in d:
    score = line["name"]
    print score

How can I display and get the value for only a specific line?

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

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

发布评论

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

评论(4

古镇旧梦 2024-10-22 23:19:56

天真的解决方案:

  target_row = 5
  for num, line in enumerate(d):
      if num == target_row:
          print line["name"]
          break

我删除了中间变量 score

请注意,这不是最佳的,因为您会迭代直到到达所需的行,但我不知道是否可以随机访问 DictReader 中的行。

Naive solution:

  target_row = 5
  for num, line in enumerate(d):
      if num == target_row:
          print line["name"]
          break

I removed the intermediate variable score.

Note that this is non-optimal, as you iterate until you reach the desired row, but I don't know if there is random access to lines in the DictReader.

〃温暖了心ぐ 2024-10-22 23:19:56

向前跳到所需的行,就像在另一个答案中一样,但在 CSV 读取迭代器上进行切片而不是手动循环:(

import csv, itertools
rownum = 20
colname = "name"
line = itertools.islice(d, rownum - 1, rownum).next()
score = line[colname]

我知道,这不是最漂亮的代码,但这只是为了说明这一点。)

Skipping ahead to the desired line, just as in the other answer, but with slicing on the CSV-reading iterator instead of a manual loop:

import csv, itertools
rownum = 20
colname = "name"
line = itertools.islice(d, rownum - 1, rownum).next()
score = line[colname]

(Not the most beautiful code, I know, but that's just to illustrate the point.)

盗琴音 2024-10-22 23:19:56

简而言之,将 csv.DictReader 的输出转换为列表格式并通过索引访问值。

注意:通过索引访问时返回的值将是一个对象,其键对应于 CSV 文件中的列名


用例:

我有类似的需求。我只想读取行的子集,例如总共 100 行中的第 10-15 行。

一个有效的简单解决方案是将其转换为列表:

# Observe that I am converting the output of DictReader into a list format
lines = list(csv.DictReader(open('somefile.csv', 'r')))

# Once I have the list of objects, I can simple access it with range
for i in range(10, 15):
    line = lines[i]
    # If you want to read the value of a specific column
    print line['column_name']

希望这有帮助。

In short, convert the output of csv.DictReader to a list format and access the values with index.

Note: The value returned when you access by index will be an object with keys corresponding to the column names in the CSV file


Use Case:

I had a similar need. I only wanted to read a subset of rows, say lines 10-15 from a total of 100 lines.

A simple solution that worked was to convert it into list:

# Observe that I am converting the output of DictReader into a list format
lines = list(csv.DictReader(open('somefile.csv', 'r')))

# Once I have the list of objects, I can simple access it with range
for i in range(10, 15):
    line = lines[i]
    # If you want to read the value of a specific column
    print line['column_name']

Hope this helps.

怪我闹别瞎闹 2024-10-22 23:19:56

如果您只知道列号和行号,您可以这样做:

TheRow = 2      # Note that row 1 is the header row
TheColumn = 2   # first column == 0
for row in d:
    if d.line_num == TheRow:
        print("row %s: %s" % (str(d.line_num), str(row) ) )
        print( row[d.fieldnames[TheColumn]] )

输出:

row 2: {'t1': '12', 't2': '23', 't3': '31'}
31

if you only know the column number and the line number you can do like this:

TheRow = 2      # Note that row 1 is the header row
TheColumn = 2   # first column == 0
for row in d:
    if d.line_num == TheRow:
        print("row %s: %s" % (str(d.line_num), str(row) ) )
        print( row[d.fieldnames[TheColumn]] )

output:

row 2: {'t1': '12', 't2': '23', 't3': '31'}
31
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文