Line Numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wocosc
    New Member
    • Mar 2007
    • 18

    #1

    Line Numbers

    Ok, lol.. I am back again. How can I get python to print line numbers if i have python already loading text from a .txt file. I just need it to print out the line numbers with the text that it is importing and printing.
  • ghostdog74
    Recognized Expert Contributor
    • Apr 2006
    • 511

    #2
    Originally posted by wocosc
    Ok, lol.. I am back again. How can I get python to print line numbers if i have python already loading text from a .txt file. I just need it to print out the line numbers with the text that it is importing and printing.
    2 ways i can think of
    1) use counter method eg
    Code:
    counter = 1
    for line in open("file"):
         print counter, line
         counter +=1
    2) use enumerate
    Code:
    for num,line in enumerate("file"):
        print num,line

    Comment

    • wocosc
      New Member
      • Mar 2007
      • 18

      #3
      Code:
      def display3():
          fname = raw_input("Enter a Filename: ")
          infile = open(fname, 'r')
          data = infile.read()
          print data
          counter = 1
          print counter, infile
          counter +=1
      so I would presume that this would work. However, when I run it, it does not print the numbers.. It prints the file, and then

      "1 <open file 'auston', mode 'r' at 0x00C3D9F8>"

      What did I do wrong?

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        Originally posted by wocosc
        Code:
        def display3():
            fname = raw_input("Enter a Filename: ")
            infile = open(fname, 'r')
            data = infile.read()
            print data
            counter = 1
            print counter, infile
            counter +=1
        so I would presume that this would work. However, when I run it, it does not print the numbers.. It prints the file, and then

        "1 <open file 'auston', mode 'r' at 0x00C3D9F8>"

        What did I do wrong?
        Python has done exactly what you have asked for.
        First, let's try to get you to start using "CODE" tags. Learn about them by reading the "POSTING GUIDELINES" on the right hand side of the page while you are posting (it there in "REPLY GUIDELINES" if you are replying). Thanks.
        Second, as my friend ghostdog74 points out, two neat tricks are to use the in operator to iterate through the file for you and couple that with the enumerate built-in fuction:
        Lastly, you don't have a loop set up, anyway:
        One way to print line numbers from 1 to n:
        Code:
        def display3():
            fname = raw_input("Enter a Filename: ")
            infile = open(fname, 'r')
            counter = 0
            data = infile.read()
            while data:
                counter += 1
                print counter, data
                data = infile.read()
        ##    print counter, infile
        or, I'll bet you could modify this to do the same thing:
        Code:
        def display3():
            fname = raw_input("Enter a Filename: ")
            infile = open(fname, 'r')
        ##    counter = 0
        ##    data = infile.read()
            for i, data in enumerate(infile):
        ##    counter +=1
                print i, data
        ##    print counter, infile

        Comment

        • runsun
          New Member
          • May 2007
          • 17

          #5
          I tried the 1st one. It worked when using ...open('file') : in line 2.
          But I have a further question:
          How does this work:
          read the 1st, 3rd ... lines, then output them in the 1st row (seperated by space);
          read the 2nd, 4th ... lines, output in the 2nd row;
          ...

          I used several loops. None of them worked.



          Originally posted by ghostdog74
          2 ways i can think of
          1) use counter method eg
          Code:
          counter = 1
          for line in open("file"):
               print counter, line
               counter +=1
          2) use enumerate
          Code:
          for num,line in enumerate("file"):
              print num,line

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            Originally posted by runsun
            I tried the 1st one. It worked when using ...open('file') : in line 2.
            But I have a further question:
            How does this work:
            read the 1st, 3rd ... lines, then output them in the 1st row (seperated by space);
            read the 2nd, 4th ... lines, output in the 2nd row;
            ...

            I used several loops. None of them worked.
            You may want to read the entire file and print them this way:[code=Python]>>> fn = 'your_file'
            >>> lineList = open(fn).readli nes()
            >>> odd_lines = [lineList[i] for i in range(len(lineL ist)) if i%2 == 1]
            >>> even_lines = [lineList[i] for i in range(len(lineL ist)) if i%2 == 0]
            >>> print ''.join(odd_lin es)
            ............... ............... .....
            >>> print ''.join(even_li nes)
            ............... ............... .....
            >>> [/code]OR[code=Python]>>> odd_lines = [lineList[i] for i in range(0,len(lin eList),2)]
            >>> even_lines = [lineList[i] for i in range(1,len(lin eList),2)][/code]You can also iterate:[code=Python]>>> f = open(fn)
            >>> odd_lines = []
            >>> even_lines = []
            >>> for i, line in enumerate(f):
            ... if i%2 == 0:
            ... odd_lines.appen d(line)
            ... else:
            ... even_lines.appe nd(line)
            ...
            >>> f.close()[/code]The above code creates a list of the even and odd lines and uses the string method join() to assemble the individual lines into one string. To get rid of the newline characters, use line.strip().

            Comment

            • runsun
              New Member
              • May 2007
              • 17

              #7
              The first one works - it seperates odd and even lines. However, the odd_lines in the output are not in one row; so are the even_lines.

              Originally posted by bvdet
              You may want to read the entire file and print them this way:[code=Python]
              >>> fn = 'your_file'
              >>> lineList = open(fn).readli nes()
              >>> odd_lines = [lineList[i] for i in range(len(lineL ist)) if i%2 == 1]
              >>> even_lines = [lineList[i] for i in range(len(lineL ist)) if i%2 == 0]
              >>> print ''.join(odd_lin es)
              ............... ............... .....
              >>> print ''.join(even_li nes)
              ............... ............... .....
              >>> [/code]OR[code=Python]>>> odd_lines = [lineList[i] for i in range(0,len(lin eList),2)]
              >>> even_lines = [lineList[i] for i in range(1,len(lin eList),2)][/code]You can also iterate:[code=Python]>>> f = open(fn)
              >>> odd_lines = []
              >>> even_lines = []
              >>> for i, line in enumerate(f):
              ... if i%2 == 0:
              ... odd_lines.appen d(line)
              ... else:
              ... even_lines.appe nd(line)
              ...
              >>> f.close()[/code]The above code creates a list of the even and odd lines and uses the string method join() to assemble the individual lines into one string. To get rid of the newline characters, use line.strip().

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                Originally posted by runsun
                The first one works - it seperates odd and even lines. However, the odd_lines in the output are not in one row; so are the even_lines.
                They are not in one row when you print them because of the newline characters. You can strip the newline characters (and other whitespace characters as well) this way:[code=Python]odd_lines = [lineList[i].strip() for i in range(0,len(lin eList),2)][/code]Add a space in between this way:[code=Python]print ' '.join(odd_line s)[/code]

                Comment

                • ghostdog74
                  Recognized Expert Contributor
                  • Apr 2006
                  • 511

                  #9
                  Code:
                  odd=[];even=[]
                  for num,line in enumerate(open("file")):
                      if num%2==0: even.append(line.strip())
                      elif num%2!=0: odd.append(line.strip())
                  print odd   
                  print even

                  Comment

                  Working...