0

I'm opening a file in Python using os.open(), and then I want to write to it using the file interface, ie. f.write().

So I'm doing the following

import os

fd = os.open('log', os.O_CREAT|os.O_RDWR, 0b111110110)
f  = open(fd,'w')

But when it's time to clean up, I don't know if I should do call both os.close(fd) and f.close(), or only one.

Calling os.close() xor f.close() is fine (ie. exactly one), but calling both throws a "bad file descriptor" error.

étale-cohomology
  • 2,098
  • 2
  • 28
  • 33
  • 2
    Why are you using `os.open` and not the built-in [`open`](https://docs.python.org/3/library/functions.html#open)? See the [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) tutorial. – Gino Mempin Feb 23 '22 at 11:58
  • Yes, you need to close it. But you can use the "with" statement and it will close automatically. https://stackoverflow.com/questions/36559580/what-is-the-purpose-of-a-context-manager-in-python/36559849#:~:text=Context%20managers%20are%20a%20way,%3E%20foo%2C%20%22Hello!%22 – Christian Weiss Feb 23 '22 at 11:59
  • 1
    Can you clarify what you are asking? The question already mentions that it's not possible to "call both ``os.close(fd)`` and ``f.close()``" so obviously you have to call "only one". Are you wondering *which* one to call? – MisterMiyagi Feb 23 '22 at 12:24
  • 2
    This can easily be found out from reading the documentation. https://docs.python.org/3/library/functions.html#open -- "If a file descriptor is given, it is closed when the returned I/O object is closed unless closefd is set to False". – Dunes Feb 23 '22 at 12:24
  • @MisterMiyagi yes, exactly – étale-cohomology Feb 23 '22 at 18:51
  • @Dunes That's exactly the type of answer I was looking for. Thank you. I was lazy and didn't even bother going over the docs, though I'll admit I didn't think they'd even mention it. I was wrong. – étale-cohomology Feb 23 '22 at 18:54

0 Answers0