Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 Python list:

stocks = open(textfile).readlines() 

However, when I look at the list in it contains Windows end-of-line delimiter which I do not want:

list: ['MMM\r\n', 'ABT\r\n', 'ABBV\r\n', 'ANF\r\n', 'ACE\r\n', 'ACN\r\n', 'ACT\r\n', 'ADBE\r\n', 'ADT\r\n', 'AMD\r\n', 'AES\r\n', ..... 

Can someone suggest the easiest way to remove these unwanted characters?

like image 632
Justin Avatar asked Jul 25 '14 01:07

Justin


People also ask

How do I remove an R from a list in Python?

You can use str. strip . '\r' is a carriage return, and strip removes leading and trailing whitespace and new line characters.

How do you remove R and N in Python?

Use the str. rstrip() method to remove \r\n from a string in Python, e.g. result = my_str. rstrip() .

How do you get rid of N in a list in Python?

Method 2: Use the strip() Function to Remove a Newline Character From the String in Python. The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\n” as a string in a string.

Does readline () take in the \n at the end of line?

In addition to the for loop, Python provides three methods to read data from the input file. The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end.


2 Answers

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)

like image 195
roippi Avatar answered Oct 07 '22 08:10

roippi


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.  
like image 33
ssm Avatar answered Oct 07 '22 06:10

ssm