我是python / repy的新手。我试图确定当前目录中的文件列表中是否存在字符串。这是我的代码。
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = false
searchString = string
for line in input:
if searchString in line:
found = true
break
if callfunc == 'initialize':
print listdir() #this will print list of files
for files in listdir():
checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
错误是什么,我该如何解决?
我在Ubuntu 12.04 LTS中运行它
Full debugging traceback:
"repy.py", line 448, in <module>
"repy.py", line 179, in main
"/home/hardik_darji/REPY/seattle/seattle_repy/virtual_namespace.py", line 78, in __init__
用户追溯:
Exception (with type 'exceptions.ValueError'): Code failed safety check! Error: ("<type 'exceptions.IndentationError'> expected an indented block (line 13)",)
答案 0 :(得分:4)
这里有很多问题:
False
和True
(Python是区分大小写的)。 SyntaxError
,但您需要将break
更深一级以使脚本正常工作。input.close()
。您的代码应为:
def checkString(filename, string):
input = file(filename) # read only will be default file permission
found = False
searchString = string
for line in input:
if searchString in line:
found = True
break
if callfunc == 'initialize':
print listdir() #this will print list of files
print "\n"
for files in listdir():
checkString(files,"hello")
if found:
print "String found"
else:
print "String not found"
input.close()
另外,我建议你不要命名变量input
- 它会掩盖内置的内容。
最后,您应该查看with
语句来处理文件。 with
是一个上下文管理器,会为您自动关闭文件。