2016-11-20 107 views
-2
print "Enter the name of the file", 
file= open(raw_input(":"),'w').write(raw_input("Enter the content:")) 
print file.read() 

作爲回答我得到AttributeError: 'NoneType' object has no attribute 'read'。請任何人都可以幫忙。爲什麼我得到一個AttributeError:'NoneType'對象沒有'read'屬性?

+4

因爲'write'不返回任何東西。分開打開並寫入文件。 – Maroun

+0

無論如何,您無法從您剛剛寫入的文件中讀取數據。 –

回答

1

write()方法不返回任何內容,因此文件值爲None。

您應該將open()函數的結果賦值給文件變量,然後在其上調用write方法。

如果您正在使用:

open(path_to_file, 'w') 

您無法讀取該文件的內容。

當你罵

file = open(some options) 

方法 你應該文件處理結束後調用

file.close() 

但是在python中有關鍵字(例如文件類)在代碼塊執行結束後自動調用close()方法,即使發生異常也是如此。 所以你的方法可以這樣實現:

def write_to_file_and_print_content(): 
    print("Enter the name of the file:") 
    name_of_file = raw_input("") 
    # Writing to file 
    with open(name_of_file, 'w') as file_to_write: 
     content_of_file = raw_input("Enter the content:\n") 
     file_to_write.write(content_of_file) 
     # after that file_to_write.close() is called 
    with open(name_of_file, 'r') as file_to_read: 
     print(file_to_read.read()) 
     # after that file_to_read.close() is called 
相關問題