Skip to content

Unexpected Behaviour when using the Built-In 'open' Function #134366

@aba-hb

Description

@aba-hb

Bug report

Bug description:

Hi!

When calling the 'open' function with a path that contains invalid symbols inside the file name, e.g. a colon, the function will truncate that path, proceed to create the file, but not write any contents to it.
What I expected to happen is that an exception is being raised and no file is created.

I don't know if this is intended behaviour and I couldn't find something about this in neither the documentation (https://docs.python.org/3/library/functions.html#open) or the PEP website.

Can somebody confirm/deny that this is a bug?

Minimal reproducible example

def main():
    from os import path
    basePath = path.dirname(__file__)
    filePath = path.join(basePath, "invalid:symbols.txt")
    fileContent = "hello world that is probably not being written to file"
    with open(filePath, "w", encoding="utf-8") as file:
        file.write(fileContent)


if __name__ == "__main__":
    main()

The above snippet results in an empty file called invalid.txt to be created.

I hope that this isn't a duplicate, I tried searching for a similar unclosed issue but couldn't find any.
In case this is expected behaviour, it would be great if it'd be mentioned in the documentation. 🥰

EDIT: Fixed the wrong file name, sorry

CPython versions tested on:

3.12, 3.13

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    OS-windowsdocsDocumentation in the Doc dirtype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions