Best method for reading newline delimited files and discarding the newlines?

后端 未结 7 1091
孤城傲影
孤城傲影 2020-11-28 03:07

I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.

What I\'ve come up with is the following c

7条回答
  •  野性不改
    2020-11-28 03:55

    What do you think about this approach?

    with open(filename) as data:
        datalines = (line.rstrip('\r\n') for line in data)
        for line in datalines:
            ...do something awesome...
    

    Generator expression avoids loading whole file into memory and with ensures closing the file

提交回复
热议问题