Why am I getting int as a return value from os.open()?

I am using the json module for something but whenever I used the json.dump or json.load functions I get an error saying int doesn’t have a .write() or .read() function. This implies that using os.open(“somefile.txt”) is giving me an int instead of the normal file obj.

If I try something like this:

import os
import json

file = os.open("Some_file.json", flags= os.RDWR | os.TRUNC)

data = {"something": "something"}

json.dump(data, file)

I get an error like this:

AttributeError: 'int' object has no attribute 'write'

I’m using Python 3.12

I tried working around it by using .dumps and .loads with the string from os.read() but .loads() doesn’t work well with the file from the string.

I tried something like this:

import os
import json

file = os.open("Some_file.json", flags= os.RDONLY | os.TEXT)

raw_data = os.read(file)

decoded_data = raw_data.decode()

data = json.loads(decoded_data)

and got this:

  raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Is there any way to get a normal file object again or is there a way to work around this problem?

  • 3

    os.open() is documented to return a file descriptor, which is an integer. If you want to convert that to a Python file object, call os.fdopen(file, "w")

    – 

  • 5

    Why not just use open()? You can use os.fdopen() if you need to convert a file descriptor, but it seems obvious to use open() when you can.

    – 

  • I don’t see os.TEXT in the documentation. And os.read() requires 2 arguments.

    – 

  • os.RDONLY | os.TEXT should be os.O_RDONLY | os.O_TEXT

    – 

  • I’ve never seen os.fdopen() before. I’m not sure when but os.open() performed the job of os.fdopen(). I never realized they changed it and sites I used didn’t say anything about it. Thanks for the information.

    – 

can you open a file for writing and dump the json data

with open("Some_file.json", 'w') as file:

    data = {"something": "something"}

    json.dump(data, file)

Leave a Comment