Search code examples
python-3.xsplitline-breaks

How to detect what kind of break line in a text file in python?


My problem is the following. I have a text file with a bunch of lines in it. The problem is this text might have been created by Windows or Unix or Mac.

I want to open this text in python (as a string block) and split according to a break line to get an array at the end with all lines. The problem is I only tested this with a windows created file so I can split the string block easily according \n. But if I understand correctly other environnement use \r \r\n ...Etc I want a general solution where I can detect what kind of line break is used in a file before I start splitting in order to split it correctly. Is that possible to do?

thanks;


Solution

  • UNIX_NEWLINE = '\n'
    WINDOWS_NEWLINE = '\r\n'
    MAC_NEWLINE = '\r'
    

    This will be how the different os apply line breaks in a file and how python sees it