写()在文件的开始? [英] write() at beginning of file?

查看:136
本文介绍了写()在文件的开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

我现在这样做,但是我希望它在文件的开头写入。 f =打开('out.txt','a')#或'w'?
f.write(string 1)
f.write(string 2)
f.write(string 3)
f.close()

使 out.txt 的内容为:


$ b

  string 3 
string 2
string 1

而不是(像这样的代码):

  string 1 
string 2
string 3


解决方案

请看这个问题。这里有一些解决方案。

虽然我可能会按照Daniel和MAK的建议 - 也许会做一个小班,让事情变得更加灵活和明确:

  class Prepender:

def __init __(self,fname,mode ='w'):
self .__ write_queue = []
self .__ f = open(fname,mode)

def write(self,s):
self .__ write_queue.insert 0,s)

def close(self):
self .__ exit __(None,None,None)
$ b def __enter __(self):
返回self
$ b $ def __exit __(self,type,value,traceback):
if self .__ write_queue:
self .__ f.writelines(self .__ write_queue)
self .__ f.close()

with Prepender('test_d.out')as f:
f.write('string 1 \\\
')
f.write 'string 2 \\\
')
f.write('string 3 \\\
')


I'm doing it like this now, but I want it to write at the beginning of the file instead.

f = open('out.txt', 'a') # or 'w'?
f.write("string 1")
f.write("string 2")
f.write("string 3")
f.close()

so that the contents of out.txt will be:

string 3
string 2
string 1

and not (like this code does):

string 1
string 2
string 3

解决方案

Take a look at this question. There are some solutions there.

Though I would probably go that same way Daniel and MAK suggest -- maybe make a lil' class to make things a little more flexible and explicit:

class Prepender:

    def __init__(self, fname, mode='w'):
        self.__write_queue = []
        self.__f = open(fname, mode)

    def write(self, s):
        self.__write_queue.insert(0, s)

    def close(self):
        self.__exit__(None, None, None)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        if self.__write_queue: 
            self.__f.writelines(self.__write_queue)
        self.__f.close()

with Prepender('test_d.out') as f:
    f.write('string 1\n')
    f.write('string 2\n')
    f.write('string 3\n')

这篇关于写()在文件的开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆