Python - 反转整个文件

时间:2013-05-07 01:46:49

标签: python file reverse

我需要能够反转整个文件,或至少反转它的内容。到目前为止我的代码是:

def reverse_file(of, rf):
     oldfile = open(of, 'r')
     reversefile = open(rf, 'w')
     filedata = oldfile.read()
     rdata = str_reverse(filedata)
     reversefile.write(rdata)
     oldfile.close()
     reversefile.close()

问题是我需要定义str_reverse并且我不确定如何创建一个可以反转所有内容的函数。有什么帮助吗?

2 个答案:

答案 0 :(得分:4)

如果您要撤销整个文件,只需使用write

致电data[::-1]即可
def reverse_file(of, rf):
    with open(of) as oldfile:
        with open(rf, "w") as reversefile:
            reversefile.write(oldfile.read()[::-1])

示例:

% cat testdata
line1
line2
line3
% cat reverse_file.py
def reverse_file(of, rf):
    with open(of) as oldfile:
        with open(rf, "w") as reversefile:
            reversefile.write(oldfile.read()[::-1])

if __name__ == "__main__":
    reverse_file("testdata", "newdata")
% python reverse_file.py
% cat newdata

3enil
2enil
1enil

答案 1 :(得分:3)

支持不适合内存的文件(基于@Darius Bacon's answer):

import os
from io import DEFAULT_BUFFER_SIZE

def reverse_blocks(file, blocksize=DEFAULT_BUFFER_SIZE):
    """Yield blocks from the file in reverse order."""
    file.seek(0, os.SEEK_END) # move file position to the end
    position = file.tell()
    while position > 0:
        delta = min(blocksize, position)
        file.seek(position - delta, os.SEEK_SET)
        yield file.read(delta)
        position -= blocksize

# reverse input and write it to output
with open("input", "rb") as infile, open("output", "wb") as outfile:
    for block in reverse_blocks(infile):
        outfile.write(block[::-1])