检查字符串是否为CSV [英] Check whether string is in CSV
问题描述
我想搜索CSV文件并打印 True
或 False
,具体取决于我是否找到字符串。但是,我遇到的问题,它会返回一个假阳性,如果它发现字符串嵌入在一个较大的文本字符串。例如:如果string是 foo
和术语 foobar $ c>,它将返回
True
$ c>在CSV文件中。我需要能够返回完全匹配。
I want to search a CSV file and print either True
or False
, depending on whether or not I found the string. However, I'm running into the problem whereby it will return a false positive if it finds the string embedded in a larger string of text. E.g.: It will return True
if string is foo
and the term foobar
is in the CSV file. I need to be able to return exact matches.
username = input()
if username in open('Users.csv').read():
print("True")
else:
print("False")
我看过使用 mmap
, re
和 csv
模块函数,但我没有任何地方。
I've looked at using mmap
, re
and csv
module functions, but I haven't got anywhere with them.
另一种方法:
import re
import csv
username = input()
with open('Users.csv', 'rt') as f:
reader = csv.reader(f)
for row in reader:
re.search(r'\bNOTSUREHERE\b', username)
推荐答案
当使用 csv
模块查看csv文件时,它将以列的列表的形式返回每一行。所以如果你想查找你的字符串,你应该修改你的代码如下:
when you look inside a csv file using the csv
module, it will return each row as a list of columns. So if you want to lookup your string, you should modify your code as such:
import csv
username = input()
with open('Users.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',') # good point by @paco
for row in reader:
for field in row:
if field == username:
print "is in file"
,但由于它是一个csv文件,您可能希望用户名位于给定的列:
but as it is a csv file, you might expect the username to be at a given column:
with open('Users.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if username == row[2]: # if the username shall be on column 3 (-> index 2)
print "is in file"
这篇关于检查字符串是否为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!