簡體   English   中英

Python os.write(filehandler,data):TypeError需要整數

[英]Python os.write(filehandler, data) : TypeError An Integer Required

我得到屬性錯誤:'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()方法的“文件對象”(以及更多)。 要將文件描述符包裝在“文件對象”中,請使用fdopen()

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

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

或上下文管理器:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM