[英]Python cannot find the string in csv file
I was try to learn how to find a string or value in csv using python. 我试着学习如何使用python在csv中查找字符串或值。 i was think it's simple but when i was try to execute my code, i don't understand why my code cannot find the string what i want.
我认为它很简单,但当我尝试执行我的代码时,我不明白为什么我的代码找不到我想要的字符串。 This is my code :
这是我的代码:
import csv
with open('sample2.csv', 'rt') as baca:
read = csv.reader(baca, delimiter='\'')
for row in read:
match = row[0]
if match == "Sample":
print match
And also i was try to print "row[0]" and the result is like this : 而且我也尝试打印“row [0]”,结果是这样的:
id name number
1 Sample 0123450000007
Print a "row" without index : 打印没有索引的“行”:
{'id\tname\tnumber': '1\tSample\t0123450000007'}
The screenshot : 截图:
It looks like demilter should be a tab 看起来demilter应该是一个标签
In [9]: import csv
...:
...: with open('sample2.csv', 'rt') as baca:
...: read = csv.reader(baca, delimiter='\t')
...: for row in read:
...: match = row[1]
...: if match == "Sample":
...: print match
Sample
You could also use csv.DictReader
which makes it easier to select the item you want. 您还可以使用
csv.DictReader
,这样可以更轻松地选择所需的项目。 Assuming your CSV looks like this: 假设您的CSV看起来像这样:
id,name,number
1,Sample,234234
2,NotAMatch,567657
You can print the matching rows like this: 您可以像这样打印匹配的行:
In [159]: import csv
In [160]: with open('samples.csv') as f:
...: reader = csv.DictReader(f, delimiter='\t')
...: for row in reader:
...: if row['name'] == "Sample":
...: print(row)
...:
OrderedDict([('id', '1'), ('name', 'Sample'), ('number', '234234')])
Or a little shorter with a list comprehension: 或者更短一点的列表理解:
In [163]: with open('samples.csv') as f:
...: reader = csv.DictReader(f)
...: print([row for row in reader if row['name'] == "Sample"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.