Python .write() 更改顺序

发布于 2024-10-05 19:28:49 字数 597 浏览 3 评论 0原文

我有一些问题:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痴者 2024-10-12 19:28:50

是什么阻止您将字符频率计数循环放在 f.write(XXX) 循环之前?

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

橙味迷妹 2024-10-12 19:28:50

您可以先使用临时文件写入它,然后将“输入”数据写入 OUTPUT.txt,然后将临时文件附加到输出。
如果数据不是很大(即适合内存),您可以使用 StringIO 。对于 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()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文