Skip to content

fileinput in-place filtering deletes the file when it cannot be opened #160406

Closed

Description

@gpshead

Bug report

Bug description:

fileinput in-place filtering renames the input file to <name>.bak and then re-creates <name> for output. If opening the backup or creating the output file fails, FileInput.nextfile() still deletes the backup, which is then the only copy of the data. A file that the user owns but cannot read is enough:

import fileinput, os, tempfile

with tempfile.TemporaryDirectory() as d:
    name = os.path.join(d, 'data.txt')
    with open(name, 'w') as f:
        f.write('only copy\n')
    os.chmod(name, 0)
    try:
        with fileinput.input(name, inplace=True) as f:
            for line in f:
                print(line, end='')
    except OSError as e:
        print(type(e).__name__)
    print(os.listdir(d))

This prints PermissionError and []: both data.txt and data.txt.bak are gone. I expected the data to survive the failed open.

Related: the output file is opened with O_CREAT | O_WRONLY | O_TRUNC and then os.chmod()ed by name. Nothing should exist under that name right after the rename, but if another process creates a file or symlink there in between, the output is written through it and the mode of the input file is applied to it. Creating the output with O_EXCL and setting the mode through the descriptor would turn that into a FileExistsError.

gh-74885 is a different way to lose the original (decode errors after the output file has been created).

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. self-assigned this
    on Oct 23, 2026
  2. added
    type-bugAn unexpected behavior, bug, or error
    stdlibStandard Library Python modules in the Lib/ directory
    on Oct 23, 2026
  3. added a commit that references this issue on Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions