我得到属性错误:'int'对象没有属性'write'.
这是我脚本的一部分
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'
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 )
或者如果你不需要任何底层API,最好使用python文件
with open('foo.txt', 'w') as output_file:
output_file.write('this is test')
os.open()
返回一个文件描述符(一个整数),而不是文件对象。来自文档:
注意:该函数用于低级I/O。对于正常使用,使用内置函数
open()
,它返回一个"文件"使用read()
和write()
方法(以及更多)。把…包起来在" file object "中,使用fdopen()
.
您应该使用内置的open()
函数:
fh = open(swfname, 'w')
fh.write(data)
fh.close()
或上下文管理器:
with open(swfname, 'w') as handle:
handle.write(data)