1

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

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,但我不确定如何创建一个反转所有内容的函数。有什么帮助吗?

4

2 回答 2

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
于 2013-05-07T01:56:09.453 回答
3

支持不适合内存的文件(基于@Darius Bacon 的回答):

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])
于 2013-05-07T02:30:37.990 回答