2013-06-02 73 views
0

我得到屬性錯誤:'int'對象沒有屬性'write'。Python os.write(filehandler,data):TypeError一個整數要求

這裏是我的腳本

data = urllib.urlopen(swfurl) 

     save = raw_input("Type filename for saving. 'D' for same filename") 

     if save.lower() == "d": 
     # here gives me Attribute Error 

      fh = os.open(swfname,os.O_WRONLY|os.O_CREAT|os.O_TRUNC) 
      fh.write(data) 

     # ##################################################### 

這裏的一部分是錯誤:

Traceback (most recent call last): 
    File "download.py", line 41, in <module> 
    fh.write(data) 
AttributeError: 'int' object has no attribute 'write' 

回答

3

os.open返回文件描述符。使用os.write寫入到打開的文件

import os 
# Open a file 
fd = os.open("foo.txt", os.O_WRONLY | os.O_CREAT | os.O_TRUNC) 
# Write one string 
os.write(fd, "This is test") 
# Close opened file 
os.close(fd) 

或者更好的使用Python的文件,如果你不需要任何低級API

with open('foo.txt', 'w') as output_file: 
    output_file.write('this is test') 
1

os.open()返回一個文件描述符(整數),而不是一個文件對象。從docs

Note: This function is intended for low-level I/O. For normal usage, use the built-in function open() , which returns a 「file object」 with read() and write() methods (and many more). To wrap a file descriptor in a 「file object」, use fdopen() .

您應該使用內置open()函數:

fh = open(swfname, 'w') 
fh.write(data) 
fh.close() 

或上下文經理:

with open(swfname, 'w') as handle: 
    handle.write(data) 
+0

在這種情況下,內置的open()是不恰當的因爲它缺少傳遞標誌O_WRONLY,O_CREAT和O_TRUNC所需的低級API。海報是正確的使用os.open()。如果你不熟悉這種機制,請參閱@ oleg的答案,該答案概述了內建的open()和os.open(),並給出了何時使用os.open()的一些指導。 –

相關問題