sodiumnitrate
sodiumnitrate

Reputation: 3131

Python reads \n as string

I am using python 2.7.9, and OS X Yosemite. I have a file called list.dat, which contains the following:

item1, a
item2, b
item3, c

and I have a python script:

list=[]
f=open('list.dat','r')
for line in f.readlines():
    list.append(line.rsplit(','))

f.close()

print list

Which produces the output:

[['item1', ' a\n'], ['item2', ' b\n'], ['item3', ' c']]

Are the \ns supposed to appear in the output? If so, how can I modify the code so that they don't?

Upvotes: 0

Views: 1139

Answers (3)

Avinash Kr Mallik
Avinash Kr Mallik

Reputation: 162

You can add a replace or strip function.

And never name your list as "list" because list is a python builtin.

list1=[]
f=open('list.dat','r')
for line in f.readlines():
    list1.append(line.rsplit(',').strip('\n'))

f.close()

print list1

Upvotes: 3

Daniel
Daniel

Reputation: 42748

'\n' is the newline-character. You have to remove it manually or use the csv-module:

import csv
with open('list.dat') as f:
    data = list(csv.reader(f))
print data

Upvotes: 1

A.J. Uppal
A.J. Uppal

Reputation: 19264

The '\n' signifies a new line, which evidently is there in your text file. Thus, the '\n's are supposed to appear in the output.

Essentially, your .dat file is:

item1, a\n
item2, b\n
item3, c\n

To remove that, try the following:

list=[]
f=open('list.dat','r')
for line in f.readlines():
    list.append(line.strip('\n').rsplit(','))

f.close()

print list

This uses str.strip('\n') to remove the new-lines ('\n's) from the string.


>>> list=[]
>>> f=open('list.dat','r')
>>> for line in f.readlines():
...     list.append(line.strip('\n').rsplit(','))
... 
>>> f.close()
>>> 
>>> print list
[['item1', ' a'], ['item2', ' b'], ['item3', ' c']]
>>> 

Upvotes: 2

Related Questions