Import csv as list in python

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 need a list of ['GBP', 'USD']. However, I get the following:

['GBP', 'USD\n']

How to stop \ n from the last value?

+4
source share
1 answer

You need to break your lines, but as a pythonic way you can use csvmodule to work with csvfiles:

>>> 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 lines in the file csv, if you just need the first line in the list, you can use the next()object method reader:

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

, :

>>> import csv
>>> with open('curr.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=',')
...     print [j for i in spamreader for j in i]
+2

Source: https://habr.com/ru/post/1584927/


All Articles