def findLineParam(sprotParam, pos):
if line[:2] == sprotParam:
start = pos
while line[start] == " ":
start += 1
stop = start + 1
while stop < len(line) and not line[stop] in (" ", ";"):
stop += 1
print(line[start:stop]) # prints the correct value!
return line[start:stop] # returns None?
简要说明代码的功能是,它应该输入一个字符串(关键字),例如“ID”,并在文本文件的一行中找到它,然后它应该在空白读取到下一个“”或“;”后找到第一个值并返回这个值。我可以看到,当我打印行时,它返回的正是我想要的,但当我返回它时,它返回“无”。你知道吗
每当我将“sprotParam”改为一个输入列表(*sprotParam)时,它会返回值,但也会返回与文件中的行相对应的相等数量的“None”,我相信这表明它会在所有行上迭代并执行操作,而这是不应该的
调用函数的代码
try:
file = input("Enter filename: ")
except IOError as e:
print("That is not a recognised filename. Error given: " + str(e))
sys.exit(1) # Close the program
with open(file, 'r') as infile:
for line in infile:
ident = findLineParam("ID", 2)
如果函数必须返回某个值,则应返回一个默认值(仅在if语句中返回,因此如果不匹配此if,则不返回任何值) 我知道这不能解决你的问题,但最好是得到这个
line
不在函数的作用域内,因此需要将其作为参数传递给函数:更新
以下是代码的简化版本:
现在,如果您为
test.txt
运行此命令:它将返回
'foo'
。你知道吗正如@NoxFly所暗示的,所有路径都不会返回。你知道吗
更好的方法是使用regex而不是while循环。 例如,正则表达式将找到值。你知道吗
相关问题 更多 >
编程相关推荐