4

I am trying to import a csv file as a list:

file = open('curr.csv', 'rt')
f = file.read()
f = f.split(',')

print(f)

The csv file is only 'GBP, USD' so I want the list ['GBP', 'USD']. However the result I get is:

['GBP', 'USD\n']

How do I stop \n from appearing on the last value?

1
  • Use the csv module. Commented Apr 27, 2015 at 15:10

1 Answer 1

2

You need to strip your lines,but as a pythonic way you can use csv module for dealing with csv files :

>>> import csv
>>> with open('curr.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=',')
...     print list(spamreader)

Note that this will return a nested list of your csv file rows if you just want the firs row in a list you can use next() method of reader object :

>>> import csv
>>> with open('curr.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=',')
...     print spamreader.next() 

And if you want the whole of your rows within a list you can use a nested list comprehension :

>>> import csv
>>> with open('curr.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=',')
...     print [j for i in spamreader for j in i]
Sign up to request clarification or add additional context in comments.

5 Comments

A valid answer, but seems a bit overkill for such a simple file.
@TheBlackCat Its the correct way for dealing with csv files. note that we are not here to just give a temporary solution to OP!
I agree with Kasra. Splitting around the string wouldn't be much shorter than 3 lines either while being a lot more fragile.
@Kasra There are various "correct ways" of dealing with csv files depending on the circumstances. In this case, dealing with the csv module adds additional complexity around dealing with multiple lines. Your answer, for example, gives [['GBP', ' USD']], which isn't what the question asked for. So in this case using a simpler approach can avoid some confusion.
@TheBlackCat Yeah i noted that. i gonna to edit the answer! thanks for attention!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.