python - 如何获取行中的特定列(csv)

标签 python csv

我有这段代码:

with open(filepath, 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ')
    for row in reader:
        print(' '.join(row))

它返回:

Type,UniProt ID,Position
Sodium channel,P35498,1-123
Sodium channel,P35498,176-188
Sodium channel,P35498,234-239
Sodium channel,P35498,426-762
Sodium channel,P35498,823-830
Potassium channel ATP-sensitive inward rectifier,P48048,1-77

我希望能够将 P35498 放入字符串中以供稍后使用。我该怎么做?我也希望能够获得这些列中的任何一个,但只要有 P35498 的示例就太好了,谢谢!

如果我这样做

with open(filepath, 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    idlist = []
    for row in reader:
        idlist.append(row[1])
        print(idlist)

返回:

['UniProt ID']
['UniProt ID', 'P35498']
['UniProt ID', 'P35498', 'P35498']
['UniProt ID', 'P35498', 'P35498', 'P35498']
['UniProt ID', 'P35498', 'P35498', 'P35498', 'P35498']
['UniProt ID', 'P35498', 'P35498', 'P35498', 'P35498', 'P35498']
['UniProt ID', 'P35498', 'P35498', 'P35498', 'P35498', 'P35498', 'P48048']

最佳答案

如果您想要第 2 列中有“P35498”的行,您可以检查第 2 列并在相同时打印:

with open(filepath, 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ')
    for row in reader:
        if "P35498"==row[1]:
            print(' '.join(row))

关于python - 如何获取行中的特定列(csv),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31459298/

相关文章:

mysql - BASH - 我如何确保 csv 文件确实是 csv 文件并且其解析正确?

javascript - 立即将 csv 文件中的数据显示到 handontable

文件名中带有空格的 sqlcmd 脚本

mysql - Excel CSV 字符串未完全上传到 Excel

python - 为什么 TextIOWrapper 关闭给定的 BytesIO 流?

python - 如何使用python关闭同一应用程序的两个窗口?

python - django Rest框架使用ArrayAgg和GROUP BY进行注释

python - 使用 python 正则表达式从字符串中提取名称

python - 在python中 pretty-print xml时如何缩进属性?

csv - 使用 awk 从 5gb 文件中输出数据