如何获取 csv 文件的特定字段?
我需要一种方法来获取 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
按照此处对SO问题的评论,最好的,更强大的代码是:
更新:如果OP实际想要的是csv文件最后一行中的最后一个字符串,则有几种不一定需要的方法csv。例如,
这对于非常大的文件来说并不好,因为您将完整的文本加载到内存中,但对于小文件来说可能没问题。请注意,
laststring
可能包含换行符,因此在使用前将其删除。最后,如果 OP 想要的是第 n 行中的第二个字符串(对于 n=2):
更新 2: 现在,这与 JFSebastian 的答案中的代码相同。 (功劳归于他):
Following the comments to the SO question here, a best, more robust code would be:
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,
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):
示例
注意:
list(csv.reader(f))
将整个文件加载到内存中。为了避免这种情况,您可以使用itertools:Example
Note:
list(csv.reader(f))
loads the whole file in memory. To avoid that you could useitertools
:此示例在 Python 3 中打印单元格 4、8。
This example prints cell 4, 8 in Python 3.
关于 csv.reader() 对象,您需要了解一个有趣的点。 csv.reader 对象不是
list
类型,并且不可下标。这是可行的:
这不行:
因此,您首先必须转换为列表类型才能使上述代码工作。
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:
This does not:
So, you first have to convert to list type in order to make the above code work.
以下可能就是您正在寻找的内容:
Following may be be what you are looking for:
终于我明白了!!!
Finaly I got it!!!