Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回值帮助Python_Python - Fatal编程技术网

返回值帮助Python

返回值帮助Python,python,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, possi

我在打印一个函数的返回值时遇到问题

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 main():
    ''' Read and print a file's contents. '''
    file = input(str('Name of file? '))
    read_contents = readfile(file)
    print read_contents

这应该可以做到,只需将函数调用分配给变量即可

但是,如果引发异常,则不返回任何内容,因此函数将返回
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
和use语句处理文件时,它负责关闭文件:

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

这是最简单的方法,我不建议在函数中添加一个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()
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()