1

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

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

4 回答 4

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()
于 2012-10-30T21:25:20.867 回答
0

你有没有尝试过:

def main():
    ''' Read and print a file's contents. '''
    file = input(str('Name of file? '))
    read_contents = readfile(file)
    print read_contents
于 2012-10-30T20:00:24.047 回答
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
于 2012-10-30T20:00:39.230 回答
0
def main():
    ''' Read and print a file's contents. '''
    file = input(str('Name of file? '))
    text = readfile(file)

    print text
于 2012-10-30T20:00:44.143 回答