#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2005
    Posts
    10
    Rep Power
    0

    how do i read just the last line of a text file?


    Hey there.
    i want to set a variable to represent the last line of a text file
    how do i do that?
    or even better, how do i create a list of the lines of a text file?
    any suggestions?
    thanks
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Location
    There where the rabbits jump
    Posts
    556
    Rep Power
    11
    you can create a list of all lines with .readlines()
    Those people who think they know everything are a great annoyance to those of us who do.
  4. #3
  5. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154
    Code:
    file_data = []
    for line in file('your_file_name_here').readlines():
        file_data.append(line)
    last_line = file_data[-1]
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2005
    Posts
    10
    Rep Power
    0
    whoa, thanks for the help guys !
    got it working now.
    thanks again.
  8. #5
  9. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Originally Posted by †Yegg†
    Code:
    file_data = []
    for line in file('your_file_name_here').readlines():
        file_data.append(line)
    last_line = file_data[-1]
    Sorry Yegg but this is about as convoluted as you can get without adding a few conditional statements in there: read the lines in the file and iterate over each line again appending it to another list . Then slice of the last element.

    This could be made much simpler:

    Code:
    lastLine = file('sample.txt', 'r').readlines()[-1]
    Take care,

    Mark.
    programming language development: www.netytan.com Hula

  10. #6
  11. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154
    Nice coding netytan. I just got owned...

IMN logo majestic logo threadwatch logo seochat tools logo