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 lin开发者_如何学Pythone:
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)"
What is preventing you from putting the character-frequency-counting loop before the f.write(XXX) loop?
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()
精彩评论