Removing \r\n from a Python list after importing with readlines

前端 未结 4 1565
别跟我提以往
别跟我提以往 2020-12-31 01:50

I have saved a list of ticker symbols into a text file as follows:

MMM
ABT
ABBV
ANF
....

Then I use readlines to put the symbols into a Pyt

相关标签:
4条回答
  • 2020-12-31 02:00

    You could do it like this:

    stocks = open(textfile).read().splitlines()
    
    0 讨论(0)
  • 2020-12-31 02:04

    That's basically how readlines works. You could post-process it:

    stocks = [x.rstrip() for x in stocks]
    

    But I prefer not using readlines at all if I don't want EOL character(s), instead doing:

    stocks = open(textfile).read().splitlines()
    

    Or even better:

    with open(textfile) as f:
        stocks = f.read().splitlines()
    

    (it almost certainly won't make a difference here, but using context managers to explicitly close file objects is a good habit to get into)

    0 讨论(0)
  • 2020-12-31 02:14

    You could replace \r\n with the empty string in a replace command.

    stocks = [x.replace("\r\n","") for x in stocks]
    
    0 讨论(0)
  • 2020-12-31 02:17

    readlines() should never be used unless you know that the file is really small. For your application, it is better to use rstrip()

    with open(filename, 'r') as f:
        for l in f:
            l = l.rstrip()
            # other operations. 
    
    0 讨论(0)
提交回复
热议问题