2013-05-07 42 views
1

我需要能夠反轉整個文件,或至少它的內容。到目前爲止我的代碼是:Python - 反轉整個文件

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,我不知道如何創建一個反轉的一切功能。任何幫助?

+0

你只是想要每一行都被顛倒過來嗎?還是你想用最後一行切換第一行還是兩者? – 2013-05-07 01:49:39

+0

@NolenRoyalty一切都應該顛倒,不太清楚如何去做。 – 2013-05-07 01:50:33

回答

4

如果要扭轉整個文件,你可以叫writedata[::-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 
+2

+1,'打開(of)as oldfile,打開(rf,「w」)爲reversefile:'也可以正常工作。 – 2013-05-07 02:05:15

+0

@AshwiniChaudhary謝謝,我想知道如果你想在同一行上使用'with',語法會是什麼樣子。 – 2013-05-07 02:08:04

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]) 
+0

+1非常好的解決方案。 – jamylak 2013-05-07 05:52:27