This question has to do with the answer to Write file with specific permissions in Python for opening a file for writing (in python) with specific permissions.
The code in the answer looks like:
with os.fdopen(os.open('foo', os.O_APPEND | os.O_CREAT, 0o644)) as out:
out.write("hello\n")
This code in 2.7.1 (my company does not have 2.7.3 installed) produces:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IOError: File not open for writing
os.fdopen
has its own mode argument, but setting that doesn't help:
>>> with os.fdopen(os.open('foo', os.O_APPEND | os.O_CREAT, 0o644), 'a') as out:
... out.write("hello\n")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
Long story short, I have not been able to figure out how to actually write to a file that has been opened via os.fdopen
and os.open
. Any ideas? Known bug in 2.7.1?
Thanks in advance!
fdopen(fd, "w+") # Tell the current position print "Current I/O pointer position :%d" % fo. tell() # Write one string fo. write( "Python is a great language. \nYeah its great!!\
OS module in Python provides functions for interacting with the operating system. OS comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. os. write() method in Python is used to write a bytestring to the given file descriptor.
open() method in Python is used to open a specified file path and set various flags according to the specified flags and its mode according to specified mode. This method returns a file descriptor for newly open file.
The os.name method in Python get the name of the underlying operating system (OS). This is a method of the OS module. The following are the operating systems that are currently registered. RISC OS. Portable Operating System Interface (POSIX)
You must choose one of O_RDONLY, O_WRONLY or O_RDWR as a "basic" mode argument to open().
You did not explicitly do so, so O_RDONLY (zero on many systems) is assumed. Python's os.fdopen
sees that you have specified a O_RDONLY and O_APPEND, which is a bit silly. Python complains about this combination with the EINVAL ("Invalid argument") error you see.
(Indeed, if you strace(1)
your script — I'm assuming Linux here — I suspect you'll see that no "natural" EINVAL is encountered. Instead, python performs your os.open()
/open(2)
, and then checks flags (F_GETFL) on the file descriptor just before raising the exception.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With