2012-10-30 106 views
1

林打印時遇到問題在我的職務返回值幫助的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的返回值的變量的值一個返回值?

回答

0

你試過:

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

@JonClements謝謝,小姐編輯。 :) –

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

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