Python .write() 更改顺序
我有一些问题:
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()
如你所见,我有 2x 写入“函数”,如何更改 txt 文件中的写入顺序;我想先写“input”,然后写“f.write(XXX)”
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)"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是什么阻止您将字符频率计数循环放在 f.write(XXX) 循环之前?
What is preventing you from putting the character-frequency-counting loop before the f.write(XXX) loop?
您可以先使用临时文件写入它,然后将“输入”数据写入 OUTPUT.txt,然后将临时文件附加到输出。
如果数据不是很大(即适合内存),您可以使用 StringIO 。对于 Python 2.7:
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: