scriptdiddy
scriptdiddy

Reputation: 1265

Python List Bracket Removal

So I am trying to add a list of ticker symbols from a CSV file into a python list.

The CSV File looks like this:

AAPL
XOM
EMC

When working with the stockList[]. How do I remove the [' '] brackets and quote marks?

My code is below:

stockList = []
csvReader = csv.reader(open('tickers.csv','rb'), quoting=csv.QUOTE_NONE)
for row in csvReader:
    stockList.append(row)

for item in stockList:
    print repr(item)

For example when the code above is ran it outputs:

['AAPL']
['XOM']
['EMC']

Upvotes: 1

Views: 5601

Answers (2)

tkone
tkone

Reputation: 22728

Just use readlines if your data is just a text file with a line-break after each symbol

fh = open('tickers.txt', 'rb')
stockList = [x.rstrip('\n') for x in fh]

That will return you:

['AAPL', 'XOM', 'EMC']

Much easier.

Upvotes: 3

Senthil Kumaran
Senthil Kumaran

Reputation: 56823

It looks like CSVReader is returning a list of rows. Modify your code in this way.

for row in csvReader:
    row = "".join(row)
    stockList.append(row)

Upvotes: 2

Related Questions