在文件开头写()?

时间:2010-04-20 18:25:47

标签: python file-io

我现在这样做了,但是我想让它在文件的开头写一下。

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

以便out.txt的内容为:

string 3
string 2
string 1

而不是(像这段代码一样):

string 1
string 2
string 3

4 个答案:

答案 0 :(得分:13)

看看this question。那里有一些解决方案。

虽然我可能会像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)

    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')

答案 1 :(得分:7)

你可以在每次写入之间抛出f.seek(0)(或者写一个为你做的包装函数),但是没有简单的内置方法。

编辑:这不起作用,即使您在其中放置f.flush()也会不断覆盖。您可能只需排队写入并自行撤销订单。

所以而不是

f.write("string 1")
f.write("string 2")
f.write("string 3")

也许可以这样做:

writeList = []
writeList.append("string 1\n")
writeList.append("string 2\n")
writeList.append("string 3\n")
writeList.reverse()
f.writelines(writeList)

答案 2 :(得分:1)

阐述Daniel DiPaolo的回答:

只需将您要写入的所有行附加到list即可。反转list,然后将其内容写入文件。

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

l=[]
l.append("string 1")
l.append("string 2")
l.append("string 3")

for line in l:
    f.write(line)

f.close()

您还可以使用deque并在其开头添加行,而不是使用list并将其反转。

答案 3 :(得分:1)

kdtrv答案的变体。此版本保留现有文件内容,并提供保留行顺序的write_lines方法。

class Prepender(object):
    def __init__(self,
                 file_path,
                ):
        # Read in the existing file, so we can write it back later
        with open(file_path, mode='r') as f:
            self.__write_queue = f.readlines()

        self.__open_file = open(file_path, mode='w')

    def write_line(self, line):
        self.__write_queue.insert(0,
                                  "%s\n" % line,
                                 )

    def write_lines(self, lines):
        lines.reverse()
        for line in lines:
            self.write_line(line)

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

    def __enter__(self):
        return self

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


with Prepender('test_d.out') as f:
    # Must write individual lines in reverse order
    f.write_line('This will be line 3')
    f.write_line('This will be line 2')
    f.write_line('This will be line 1')

with Prepender('test_d.out') as f:
    # Or, use write_lines instead - that maintains order.
    f.write_lines(
        ['This will be line 1',
         'This will be line 2',
         'This will be line 3',
        ]
    )