abdoulsn
abdoulsn

Reputation: 1159

Saving for loop output into txt

Im stuck in saving this for loop results, I've searched in stack all kind to save output of the for loop but I did come a the right solution. My code is:

doc = sys.argv[1]
target = sys.argv[2]
fene = int(sys.argv[3])

a = open(file)
text = a.read() 
a.close()

tokens = text.split()
keyword = re.compile(target, re.IGNORECASE)

for index in range( len(tokens) ):
    if keyword.match( tokens[index] ):
        start = max(0, index-window)
        finish = min(len(tokens), index+window+1)
        lhs = " ".join( tokens[start:index] )
        rhs = " ".join( tokens[index+1:finish] )
        print("%s \t \t %s \t \t %s" % (lhs, tokens[index], rhs)) 

I tried f = open("output.txt", w) then at the end(line print) i've added f.write(lsm, tokens[index], rhs) this did not work. Even bringing open() into for loop. How too handle it? UPDATE: output of for loop that I want in txt. image

Upvotes: 2

Views: 596

Answers (1)

abdoulsn
abdoulsn

Reputation: 1159

@Michael answer explanation in comment. Thanks

saveme = open('output.txt', 'w') 
for index in range( len(tokens) ):
    if keyword.match( tokens[index] ):
        start = max(0, index-window)
        finish = min(len(tokens), index+window+1)
        lhs = " ".join( tokens[start:index] )
        rhs = " ".join( tokens[index+1:finish] )
        print("%s \t \t %s \t \t %s" % (lhs, tokens[index], rhs), file=saveme)
saveme.close()

Upvotes: 1

Related Questions