Python-Create array from txt
<p>I'm trying to create an array of stock tickers in Python 2.7 from a txt file. The txt file simply has 1 ticker per line like:</p>

<pre><code>SRCE
ABTX
AMBC
ATAX
</code></pre>

<p>The code I'm using looks like:</p>

<pre><code>FinTick= []

    def parseRus():
        try:
        readFile=open(r'filename.txt','r').read()
        splitFile=readFile.split('\n')
        FinTick.append(splitFile)
        print FinTick



        except Exception, e:
        print str(e)
</code></pre>

<p>When I call 'parseRus()' I get an output that looks like:</p>

<pre><code>'\xff\xfeS\x00R\x00C\x00E\x00\r\x00', '\x00A\x00B\x00T\x00X\x00\r\x00', '\x00A\x00M\x00B\x00C\x00\r\x00', '\x00A\x00T\x00A\x00X\x00\r\x00'
</code></pre>

<p>The correct letters are present but not printing in plane text. I've used a couple other logic methods to populate the array but still get the same output format.</p>

<pre><code>&gt;&gt;&gt; tickers = []
&gt;&gt;&gt; with open("filename.txt", "r") as f:
        for ticker in f.readlines():
            tickers.append(ticker.strip())


&gt;&gt;&gt; tickers
['SRCE', 'ABTX', 'AMBC', 'ATAX']
</code></pre>

<p>Try using <code>readlines()</code> and <code>strip()</code> instead.</p>

<p>Edit: Some clarity around <code>f.readlines()</code> and <code>strip()</code>:</p>

<pre><code>&gt;&gt;&gt; with open("filename.txt", "r") as f:
        print(f.readlines())

['SRCE\n', 'ABTX\n', 'AMBC\n', 'ATAX']
</code></pre>

<p>So, when we're iterating through the <code>list</code> object returned by <code>f.readlines()</code>, we will need to strip the newline <code>\n</code> characters. Use the <code>strip()</code> method for <code>str</code> types to do this.</p>

<p>Edit 2: @Eli is right. We can just use <code>for ticker in f</code> instead of <code>for ticker in f.readlines()</code>, too.</p>

<pre><code>&gt;&gt;&gt; tickers = []
&gt;&gt;&gt; with open("filename.txt", "r") as f:
        for ticker in f:
            tickers.append(ticker.strip())

&gt;&gt;&gt; tickers
['SRCE', 'ABTX', 'AMBC', 'ATAX']
</code></pre>

python arrays python-2.7