How can I alter the universal line ending behavior globally?

Viewed 47

I want to write out all text files with LF as ending instead of CRLF on Windows. Not just for my code, but for all other third-party dependencies as well.

I know I can just open(..., newline='\n', ...) for my codes. But there are external packages that write files and they open() without such options, so those files are opened in universal line ending mode and ends up being written in CRLF.

How can I change the default behavior from CRLF to LF on Windows? Apparently trying to overwrite os.linesep = '\n' didn't work.

1 Answers

You could monkey-patch open:

import builtins

orig_open = open


def my_open(
    file,
    mode="r",
    buffering=-1,
    encoding=None,
    errors=None,
    newline=None,
    closefd=True,
    opener=None,
):
    return orig_open(
        file,
        mode,
        buffering,
        encoding,
        errors,
        newline="\n",
        closefd=closefd,
        opener=None,
    )


builtins.open = my_open
Related