-2

Is there a way to read a text file in reverse for Python 2.2? Thanks for the help =)

  • 2
    Please show us [what have you tried](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Iswanto San Apr 09 '13 at 02:31
  • As a note, none of the answers in the duplicate question answer this one since they all use features > 2.2. Apart from maybe the very low level answers, which are complete overkill. – Serdalis Apr 09 '13 at 07:26

1 Answers1

0

try the following.

# method not using the `reverse` function
def read_file_reversed(filename):
    return open(filename, 'r').readlines()[::-1]

It reverses the list using slicing.
Be mindful that these will load the entire file into memory.

Serdalis
  • 10,296
  • 2
  • 38
  • 58
  • 2
    I believe you mean `reversed`, which was released in 2.4. Also, files have a `readlines` method which returns a list, so there is no need for the list comprehension. – Steven Rumbalski Apr 09 '13 at 03:28
  • @StevenRumbalski I meant `list.reverse()` but misread it in the docs. Where would I find when that was introduced? I usually use list comprehension to allow for extra processing as the list is being constructed, but you're correct its not needed here. – Serdalis Apr 09 '13 at 04:33
  • 1
    @Serdalis: just search for reversed in the latest python doc. http://docs.python.org/2/library/functions.html#reversed says new in 2.4 – Anthon Apr 09 '13 at 04:34
  • @Anthon heh I feel stupid for missing that, thanks. I'll update my answer. – Serdalis Apr 09 '13 at 04:37
  • 1
    @Serdalis: older docs are still available, just not made with sphinx. http://docs.python.org/release/2.2/ – Anthon Apr 09 '13 at 04:38
  • Does the filename only put the name of the file with the extension or the whole file directory. I am very noob in python. Started a few weeks ago. – Salihin Alim Apr 09 '13 at 05:34
  • @SalihinAlim filename does include the directory :) – Serdalis Apr 09 '13 at 06:02