This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Using a dictionary for open files.
Type: behavior Stage: resolved
Components: IO Versions: Python 3.9, Python 3.8
process
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Keepun, eryksun
Priority: normal Keywords:

Created on 2021-12-29 12:34 by Keepun, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg409303 - (view) Author: Keepun (Keepun) Date: 2021-12-29 12:34
"""
Using a dictionary for open files.

The file is filled with NULL. Only the last entry is normal.

Result:
00 00 00 00 ... 00 0A 48 65 6C 6C 6F 0A

Ubuntu - 3.8.10
Windows - 3.9.8
"""
fhandles = {}
for f in range(100):
    fh = fhandles.setdefault("suffix", open(r"test.txt", "w"))
    fh.write("\nHello\n")
    fh.flush()
for f in fhandles.values():
    f.close()

import sys
print(sys.version_info)
msg409305 - (view) Author: Eryk Sun (eryksun) * (Python triager) Date: 2021-12-29 13:15
Every time open(r"test.txt", "w") is called, the existing "test.txt" file gets overwritten in the filesystem as an empty file. For each iteration, setdefault() returns a reference to the first file object, which advances its file pointer with each fh.write("\nHello\n") call. For the last write, the file pointer is at offset 693 (i.e. 7 * 99), and the OS first writes null bytes up to the file pointer. This is normal behavior, not a bug.
msg409308 - (view) Author: Keepun (Keepun) Date: 2021-12-29 13:53
I didn't think about calculating the argument before passing it to the function...
History
Date User Action Args
2022-04-11 14:59:53adminsetgithub: 90351
2021-12-29 13:53:00Keepunsetstatus: open -> closed

messages: + msg409308
stage: resolved
2021-12-29 13:15:12eryksunsetnosy: + eryksun
messages: + msg409305
2021-12-29 12:34:59Keepuncreate