python-2.7 - 使用python在文件中搜索字符串
问题描述
我需要做很多'grep -i str file'
回馈的事情,但多年来我一直在努力解决这个问题。
我有一个名为“siteLookup”的函数,我正在传递两个参数:str 's' 和 file_handle 'f'。我想a)确定字符串是否(在此示例中)出现(单个)site="XX001"
,并且b)如果找到,则取它所在的行,并返回我从中提取的另一个字段值[找到]线回呼叫者。(这是一个“csv”查找)。我定期进行此工作,但随后它将停止工作,我不明白为什么。
我已经尝试了所有不同的“开放”选项,包括 f.readlines 等。
#example line: 'XX001,-1,10.1.1.1/30,By+Location/CC/City Name/'
#example from lookupFile.csv: "XX001","Charleston","United States"
sf = open('lookupFile.csv')
def siteLookup(s, f):
site = s.split(',')[0].strip().upper()
if len(site) == 5:
f.seek(0)
for line in f:
if line.find(site)>=0:
city = line.split(',')[1].strip('"').upper()
return city
# else site not found
return -1
else: # len(site) != 5
return -1
city = siteLookup(line, sf)
print(city)
sf.close()
我在这段代码中得到零匹配。(我已将此示例代码简化为单个搜索)。我期待取回与 5 位站点代码匹配的城市名称 - 站点代码是示例“行”中的第一个字段。
非常感谢任何帮助。
解决方案
你return
的缩进错误——如果你要找的东西在第一行没有找到,它会返回 -1 并且不再看。
用于with open(...) as f:
使您的代码更安全:
with open("lookupFile.csv","w") as f: f.write("""#example from lookupFile.csv: "XX001","Charleston","United States" """)
def siteLookup(s, f):
site = s.split(',')[0].strip().upper()
if len(site) == 5:
f.seek(0)
for line in f:
if site in line: # if site in line is easier for checking
city = line.split(',')[1].strip('"').upper()
return city
# wrongly indented - will return if site not in line
# return -1
# if too short or not found, return -1 - no need for 2 returns
return -1
line = 'XX001,-1,10.1.1.1/30,By+Location/CC/City Name/'
with open('lookupFile.csv') as sf:
city = siteLookup(line, sf)
print(city)
输出:
CHARLESTON
推荐阅读
- javascript - iframe vimeopro 视频位置不适用于 Vanilla.js 水平滚动?
- javascript - 函数返回之前的对象,findById() 用需要的数据填充它
- c++ - 无法从 PPP 示例代码中找到calculator01.cpp
- ios - 在 iOS 应用中使用远程配置 Firebase
- python - 对于 Dijkstra 的算法,我缺少什么边缘情况?
- python - Python:在嵌套字典列表中搜索嵌套字典列表
- javascript - 在文本框中按回车后如何触发“添加”按钮?
- c# - 从文件到二维字符数组末尾的文本
- python - 在不同的子图中绘制不同组的数据框
- c# - 无法使用依赖注入解析服务类型