返回值帮助Python

时间:2012-10-30 19:58:12

标签: python

我无法打印其中一个函数的返回值

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返回值的变量值?

4 个答案:

答案 0 :(得分:2)

这是最简单的方法,我不建议在函数中添加一个try块,因为你不得不在之后使用它或者返回一个空值,这是一件坏事

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

答案 1 :(得分:0)

你试过了吗?

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

答案 2 :(得分:0)

这应该这样做,只需将函数调用赋值给变量。

但是如果引发异常,你什么也没有返回,所以函数将返回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

答案 3 :(得分:0)

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

    print text