Thread: counting lines

    #1
  1. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407

    counting lines


    Can some one give me a sample on how to count lines in a txt file.. or etc
  2. #2
  3. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407
    never mind i got it working using some php skils =)
    sort off ... anyways check it

    Code:
    fopen  =  open("1.txt", "r")
    read   =  fopen.read()
    count  = 0
    
    for enter in read:
     if enter == "\n":
      count = count + 1
      
    print count
    is this the best way to do it.. or is there a better way?
  4. #3
  5. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    As with most things, Python makes it very easy, not too mention quite attractive.. all you need to do this is these 15 lines of code, oh wait, this is only one line

    Code:
    count = len(file('file.txt', 'r').readlines())
    Mark.
    programming language development: www.netytan.com Hula

  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Oh while i think about it heres another ways too do this (although id recommend the first one), i've included this one because it demenstrates the use of the string types count(string) method (which can be pretty useful sometimes!)

    Code:
    count = file('file.txt', 'r').read().count('\n')
    Note: this may not always return the same as the first example since example one counts the number of lines while this one counts the number of '\n' in the file.

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

  8. #5
  9. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407
    hey thanx =)

IMN logo majestic logo threadwatch logo seochat tools logo