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

前端 未结 2 1948
孤街浪徒
孤街浪徒 2021-01-01 17:36

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:11

    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')
    

提交回复
热议问题