2012-08-06 64 views
0

我想在Python中使用File.read()函數將文件內容輸出到終端,但繼續收到與我的「.txt」文件內容不匹配的以下輸出。Python的file.read()函數輸出?

Python代碼

from sys import argv 
script, input_file = argv 

def print_all(f): 
    print f.read 

current_file = open(input_file) 
print "Print File contents:\n" 
print_all(current_file) 
current_file.close() 

輸出:

Print File contents: 

<built-in method read of file object at 0x1004bd470> 
+3

你已經回答了你自己的問題。你只是說你正在嘗試執行「File.read()」,然而在你的代碼中,你執行了「File.read」 – 2012-08-06 14:45:47

+3

+ 1來抵消(在我看來)不合理的downvote。這是一個合法的問題(一個常見的錯誤,特別是如果你來自Ruby背景,括號是可選的)。 – 2012-08-06 14:46:10

回答

5

如果你想通話一個功能,您將需要()函數的名稱後(與任何一起所需參數)

因此,在你的函數print_all取代:

print f.read # this prints out the object reference 

有:

print f.read() # this calls the function 
0

你應該做一個read()

current_file = open(input_file) 
print "Print File contents:\n" 
print_all(current_file.read()) 
1

你只需要改變

print f.read 

print f.read() 
0

您需要實際調用該函數在print_all定義:

def print_all(f): 
    print f.read() 
0

您還沒有叫read方法,你拿到它從文件類。爲了稱它,你必須把大括號。 f.read()