1

I get Attribute Error: 'int' object has no attribute 'write'.

Here is a part of my script

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)

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

Here is error:

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

2 Answers 2

3

os.open returns file descriptor. Use os.write to write into open file

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 )

Or better use python files if You don't need any low level API

with open('foo.txt', 'w') as output_file:
    output_file.write('this is test')
Sign up to request clarification or add additional context in comments.

Comments

1

os.open() returns a file descriptor (an integer), not a file object. From the 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().

You should use the builtin open() function instead:

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

Or a context manager:

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

1 Comment

In this situation, the builtin open() is not appropriate because it lacks the low-level API necessary to pass the flags O_WRONLY, O_CREAT, & O_TRUNC. The poster is correct to use os.open(). In case you're not familiar with this mechanism, see @oleg's answer, which outlines both the builtin open() and os.open(), and gives some guidance as to when to use os.open().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.