Python 文件操作的语法错误
我是python/repy新手。我试图确定当前目录中的文件列表中是否存在字符串。这是我的密码Python 文件操作的语法错误,python,file,Python,File,我是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 = t
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"
错误是什么?我如何解决它
我在Ubuntu12.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__
完全调试回溯:
“repy.py”,第448行,在
“repy.py”,第179行,主体部分
“/home/hardik_darji/REPY/settle/settle_REPY/virtual_namespace.py”,第78行,在__
用户回溯:
Exception (with type 'exceptions.ValueError'): Code failed safety check! Error: ("<type 'exceptions.IndentationError'> expected an indented block (line 13)",)
Exception(类型为“exceptions.ValueError”):代码未通过安全检查!错误:(“应为缩进块(第13行)”,)
这里有很多问题:
False
和True
(Python区分大小写)李>
中断
更深一层才能使脚本正常工作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
是一个上下文管理器,它将为您自动关闭文件。“出现了什么错误”-您应该告诉我们。@PaulGriffiths。刚刚发布it@iCodez,谢谢你的解答。但它在终端输出上没有打印任何内容。为什么?我做了如图所示的更改。非常感谢。但它不会在命令行中打印任何内容。为什么?他可以用文件关闭文件。关闭或用with
语句关闭,这几乎总是一个更好的选择。@Hardik你在调用函数吗?如果找到该代码,该代码会到达吗:
检查?在这之前它递归地调用自己(至少如果listdir()
是非空的),不是吗?