语法错误文件操作

时间:2013-10-12 22:43:11

标签: 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 = 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)",)

1 个答案:

答案 0 :(得分:4)

这里有很多问题:

  1. 您在for循环,if语句和else语句结束时缺少冒号。
  2. 你拼错了FalseTrue(Python是区分大小写的)。
  3. 您的缩进已关闭(不确定这是否只是SO格式错误)。
  4. 虽然它不会导致SyntaxError,但您需要将break更深一级以使脚本正常工作。
  5. 您需要执行input.close()
  6. 关闭文件

    您的代码应为:

    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是一个上下文管理器,会为您自动关闭文件。