1

I need to be able to reverse a whole file, or at least the contents of it. My code so far is:

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

The problem is I need to define str_reverse and I'm not sure how to create a function that reverses everything. Any help?

Thad Smith
  • 55
  • 1
  • 2
  • 8

2 Answers2

4

If you want to reverse the entire file, you can just call write with data[::-1]

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

example:

% 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
Nolen Royalty
  • 18,415
  • 4
  • 40
  • 50
3

To support files that do not fit in memory (based on @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])
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670