thaking
thaking

Reputation: 3635

Python .write() change order

I have some problem:

f = open('OUTPUT.txt', 'w')

def function
    if  ........
      ......
   f.write(XXX)                 #this must be in this loop         #1.write
    else:
      ....
      ....

....other code...
................

with open("INPUT.txt") as f_in:
    for line in f_in:
        for char in line:
            frequencies[char] += 1
input= [(count, char) for char, count in frequencies.iteritems()]

f.write(' '.join("%s=%s" % (y, x) for x,y in input))            #2.write

f.close()

As you can see, I have 2x write "function", how can I change writting order in txt file; I want to write first "input", then "f.write(XXX)"

Upvotes: 0

Views: 727

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56674

What is preventing you from putting the character-frequency-counting loop before the f.write(XXX) loop?

Upvotes: 1

Piotr Lopusiewicz
Piotr Lopusiewicz

Reputation: 2594

You could use temp file to write to it first, then write 'input' data to OUTPUT.txt, then append temp file to output.
If the data isn't huge (ie. will fit in memory) you could use StringIO for that. For Python 2.7:

import StringIO
temp = StringIO.StringIO()  
write xxx to temp file here  
...  
write 'input' data to output file here  
temp.seek(0) # sets current position in file to it's beginning  
for line in temp:  
    output.write(line)
temp.close()  
output.close()

Upvotes: 0

Related Questions