返回值帮助Python



im在打印我的一个功能之一的返回值

很难
def readfile(filename):
    '''
    Reads the entire contents of a file into a single string using
    the read() method.
    Parameter: the name of the file to read (as a string)
    Returns: the text in the file as a large, possibly multi-line, string
    '''
    try:
        infile = open(filename, "r") # open file for reading
        # Use Python's file read function to read the file contents
        filetext = infile.read()
        infile.close() # close the file
        return filetext # the text of the file, as a single string
    except IOError:
        ()

def main():
    ''' Read and print a file's contents. '''
    file = input(str('Name of file? '))
    readfile(file)

如何将ReadFile的值保存到不同的变量中,然后打印您保存ReadFile的返回值的变量的值?

这是最简单的方法,我不建议在功能中添加一个尝试块,因为您无论如何都必须在之后使用它或返回一个不好的东西的空值

def readFile(FileName):
    return open(FileName).read()
def main():
    try:
        File_String = readFile(raw_input("File name: "))
        print File_String
    except IOError:
        print("File not found.")
if __name__ == "__main__":
    main()

您是否尝试过:

def main():
    ''' Read and print a file's contents. '''
    file = input(str('Name of file? '))
    read_contents = readfile(file)
    print read_contents
def main():
    ''' Read and print a file's contents. '''
    file = input(str('Name of file? '))
    text = readfile(file)
    print text

这应该做到这一点,只需将函数调用分配给变量。

但是,如果增加了例外情况,您什么也没返回,因此该功能将返回None

def main():
    ''' Read and print a file's contents. '''
    file = input('Name of file? ')           #no need of str() here
    foo=readfile(file)
    print foo

并在处理文件时使用with语句,它会处理文件的关闭:

def readfile(filename):
     try:
        with open(filename) as infile :
           filetext = infile.read()
           return filetext    
     except IOError:
        pass 
        #return something here too

最新更新