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

后端 未结 7 1092
孤城傲影
孤城傲影 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:56

    I use this

    def cleaned( aFile ):
        for line in aFile:
            yield line.strip()
    

    Then I can do things like this.

    lines = list( cleaned( open("file","r") ) )
    

    Or, I can extend cleaned with extra functions to, for example, drop blank lines or skip comment lines or whatever.

提交回复
热议问题