0

这是我的代码。当我运行它时,它只是在运行后退出。没有打印任何内容。为什么这样 ?

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()
4

2 回答 2

0

found是函数中的本地名称checkString();它保持在本地,因为您不返回它。

从函数返回变量并存储返回值:

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
    return found

for files in listdir():
    found = checkString(files,"hello")
    if found:
        print "String found"
    else:
        print "String not found"
于 2013-10-12T23:49:34.913 回答
0

您需要修改为:

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

    input.close()
    return found

found = False

if callfunc == 'initialize':
    print listdir() #this will print list of files
    print "\n"

for files in listdir():
    found = found or checkString(files,"hello")

if found:
    print "String found"
else:
    print "String not found"

这是因为在您的原始文件found中仅在函数范围内checkString

于 2013-10-12T23:51:37.700 回答