我有这段代码:
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']
答案 0 :(得分:1)
row
是一个列表,您可以使用索引来获取相应列的数据。例如,对于列ID
,即第二列,因此索引为1
,您可以使用 -
with open(filepath, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
idlist = []
for row in reader:
idlist.append(row[1])
print(idlist)
最后,idlist
将是csv中所有ID的列表。
另外,根据您的示例,您应该使用,
作为分隔符。
如问题评论中所述,如果要求打印具有特定ID的行,您可以使用 -
with open(filepath, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
if 'P35498' in row[1]:
print(' '.join(row))
答案 1 :(得分:1)
如果你想在第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))
答案 2 :(得分:0)
实际上,只是做
with open(filepath, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
uniprot_id = row[1]
print uniprot_id
作品。