Search code examples
pythonfile-ioend-of-line

Python: Specify end-of-line format for reading files


I'm writing a Python script which processes a text file. I expect to process files generated from different people, working under different operating systems. Is there a nice way to figure out which OS created the text file, and specify the end-of-line convention to make parsing line-by-line trivial?


Solution

  • Use universal newline mode when opening the file.

    with open('input.txt', 'rU') as fp:
      for line in fp:
        print line