Convert \r text to \n so readlines() works as intended

前端 未结 2 729
迷失自我
迷失自我 2021-01-01 17:49

In Python, you can read a file and load its lines into a list by using

f = open(\'file.txt\',\'r\')
lines = f.readlines()

Each individual l

相关标签:
2条回答
  • 2021-01-01 18:13

    If it's a concern, open in binary format and convert with this code:

    from __future__ import with_statement
    
    with open(filename, "rb") as f:
        s = f.read().replace('\r\n', '\n').replace('\r', '\n')
        lines = s.split('\n')
    
    0 讨论(0)
  • 2021-01-01 18:23
    f = open('file.txt','rU')
    

    This opens the file with Python's universal newline support and \r is treated as an end-of-line.

    0 讨论(0)
提交回复
热议问题