futevolei
futevolei

Reputation: 190

Reading/writing files in Python

I am trying to create a new text file of stock symbols in the russell 2k from one that looks like this:

enter image description here

All I want is the ticker symbol at the end of each line. So I have the following code:

with open("russ.txt", "r") as f:
    for line in f:
        line = line.split()
        line = line[-1]
        if line == "Ticker": continue
        print line
        with open("output.txt", "w") as fh:
            fh.seek(0,2)
            print line
            fh.write(line)

All I end up with in the output.txt file is one line with the very last ticker in the list instead of all the tickers. I thought using fh.seek(0,2) would create a new line at the end each time through. What am I doing wrong? Also, in reality I don't need to create another doc, I could just edit the current one but I couldn't figure that out either so if you could show me how to just write to the same file that also is perfectly acceptable.

Upvotes: 2

Views: 4858

Answers (4)

Daniel
Daniel

Reputation: 42758

The filemode "w" creates a new empty file in each step. Either use mode "a" for append, or move the file opening outside the loop.

with open("russ.txt", "r") as f:
    for line in f:
        line = line.split()
        line = line[-1]
        if line == "Ticker": continue
        print line
        with open("output.txt", "a") as fh:
            fh.write(line + "\n")

or better, open the file only once:

with open("russ.txt", "r") as f, open("output.txt", "w") as fh:
    for line in f:
        symbol = line.split()[-1]
        if symbol != "Ticker":
            print symbol
            fh.write(symbol + "\n")

Upvotes: 2

Iron Fist
Iron Fist

Reputation: 10951

I believe using fileinput will be also handy in your case:

import fileinput
import sys


for line in fileinput.input("russ.txt", inplace=1):
    sys.stdout.write(line.split(' ')[-1])

fileinput.input will change original file.

Upvotes: 1

letsc
letsc

Reputation: 2567

You can read the file into a list and then use the .split() method to split it along the spaces. Since the ticekr is the last element of the list. You can get it via negative indexing.

f = [line.strip() for line in open('so.txt')]
for i in f:
    print i.split(' ')[-1]

Input file:

STARK INDUSTRIES ST
STARK INDUSTRIES ST
STARK INDUSTRIES ST
STARK INDUSTRIES ST
STARK INDUSTRIES ST

Output:

ST
ST
ST
ST
ST

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

You're overwriting the file each time you open it. Move the with line outside of the for block, and seek to the end before writing (or open in append mode).

Upvotes: 0

Related Questions