使用 Python DictReader 获取特定行和值
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
天真的解决方案:
我删除了中间变量
score
。请注意,这不是最佳的,因为您会迭代直到到达所需的行,但我不知道是否可以随机访问 DictReader 中的行。
Naive solution:
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.
向前跳到所需的行,就像在另一个答案中一样,但在 CSV 读取迭代器上进行切片而不是手动循环:(
我知道,这不是最漂亮的代码,但这只是为了说明这一点。)
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:
(Not the most beautiful code, I know, but that's just to illustrate the point.)
简而言之,将 csv.DictReader 的输出转换为列表格式并通过索引访问值。
用例:
我有类似的需求。我只想读取行的子集,例如总共 100 行中的第 10-15 行。
一个有效的简单解决方案是将其转换为列表:
希望这有帮助。
In short, convert the output of csv.DictReader to a list format and access the values with index.
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:
Hope this helps.
如果您只知道列号和行号,您可以这样做:
输出:
if you only know the column number and the line number you can do like this:
output: