473,406 Members | 2,390 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Line Numbers

18
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.
Mar 7 '07 #1
8 4872
ghostdog74
511 Expert 256MB
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
Expand|Select|Wrap|Line Numbers
  1. counter = 1
  2. for line in open("file"):
  3.      print counter, line
  4.      counter +=1
  5.  
2) use enumerate
Expand|Select|Wrap|Line Numbers
  1. for num,line in enumerate("file"):
  2.     print num,line
  3.  
Mar 7 '07 #2
wocosc
18
Expand|Select|Wrap|Line Numbers
  1. def display3():
  2.     fname = raw_input("Enter a Filename: ")
  3.     infile = open(fname, 'r')
  4.     data = infile.read()
  5.     print data
  6.     counter = 1
  7.     print counter, infile
  8.     counter +=1 
  9.  
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?
Mar 7 '07 #3
bartonc
6,596 Expert 4TB
Expand|Select|Wrap|Line Numbers
  1. def display3():
  2.     fname = raw_input("Enter a Filename: ")
  3.     infile = open(fname, 'r')
  4.     data = infile.read()
  5.     print data
  6.     counter = 1
  7.     print counter, infile
  8.     counter +=1 
  9.  
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:
Expand|Select|Wrap|Line Numbers
  1. def display3():
  2.     fname = raw_input("Enter a Filename: ")
  3.     infile = open(fname, 'r')
  4.     counter = 0
  5.     data = infile.read()
  6.     while data:
  7.         counter += 1
  8.         print counter, data
  9.         data = infile.read()
  10. ##    print counter, infile 
  11.  
or, I'll bet you could modify this to do the same thing:
Expand|Select|Wrap|Line Numbers
  1. def display3():
  2.     fname = raw_input("Enter a Filename: ")
  3.     infile = open(fname, 'r')
  4. ##    counter = 0
  5. ##    data = infile.read()
  6.     for i, data in enumerate(infile):
  7. ##    counter +=1
  8.         print i, data
  9. ##    print counter, infile 
  10.  
Mar 7 '07 #4
runsun
17
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.



2 ways i can think of
1) use counter method eg
Expand|Select|Wrap|Line Numbers
  1. counter = 1
  2. for line in open("file"):
  3.      print counter, line
  4.      counter +=1
  5.  
2) use enumerate
Expand|Select|Wrap|Line Numbers
  1. for num,line in enumerate("file"):
  2.     print num,line
  3.  
May 17 '07 #5
bvdet
2,851 Expert Mod 2GB
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:
Expand|Select|Wrap|Line Numbers
  1. >>> fn = 'your_file'
  2. >>> lineList = open(fn).readlines()
  3. >>> odd_lines = [lineList[i] for i in range(len(lineList)) if i%2 == 1]
  4. >>> even_lines = [lineList[i] for i in range(len(lineList)) if i%2 == 0]
  5. >>> print ''.join(odd_lines)
  6. ...................................
  7. >>> print ''.join(even_lines)
  8. ...................................
  9. >>> 
OR
Expand|Select|Wrap|Line Numbers
  1. >>> odd_lines = [lineList[i] for i in range(0,len(lineList),2)]
  2. >>> even_lines = [lineList[i] for i in range(1,len(lineList),2)]
You can also iterate:
Expand|Select|Wrap|Line Numbers
  1. >>> f = open(fn)
  2. >>> odd_lines = []
  3. >>> even_lines = []
  4. >>> for i, line in enumerate(f):
  5. ...     if i%2 == 0:
  6. ...         odd_lines.append(line)
  7. ...     else:
  8. ...         even_lines.append(line)
  9. ...         
  10. >>> f.close()
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().
May 17 '07 #6
runsun
17
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.

You may want to read the entire file and print them this way:
Expand|Select|Wrap|Line Numbers
  1. >>> fn = 'your_file'
  2. >>> lineList = open(fn).readlines()
  3. >>> odd_lines = [lineList[i] for i in range(len(lineList)) if i%2 == 1]
  4. >>> even_lines = [lineList[i] for i in range(len(lineList)) if i%2 == 0]
  5. >>> print ''.join(odd_lines)
  6. ...................................
  7. >>> print ''.join(even_lines)
  8. ...................................
  9. >>> 
OR
Expand|Select|Wrap|Line Numbers
  1. >>> odd_lines = [lineList[i] for i in range(0,len(lineList),2)]
  2. >>> even_lines = [lineList[i] for i in range(1,len(lineList),2)]
You can also iterate:
Expand|Select|Wrap|Line Numbers
  1. >>> f = open(fn)
  2. >>> odd_lines = []
  3. >>> even_lines = []
  4. >>> for i, line in enumerate(f):
  5. ...     if i%2 == 0:
  6. ...         odd_lines.append(line)
  7. ...     else:
  8. ...         even_lines.append(line)
  9. ...         
  10. >>> f.close()
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().
May 17 '07 #7
bvdet
2,851 Expert Mod 2GB
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:
Expand|Select|Wrap|Line Numbers
  1. odd_lines = [lineList[i].strip() for i in range(0,len(lineList),2)]
Add a space in between this way:
Expand|Select|Wrap|Line Numbers
  1. print ' '.join(odd_lines)
May 17 '07 #8
ghostdog74
511 Expert 256MB
Expand|Select|Wrap|Line Numbers
  1. odd=[];even=[]
  2. for num,line in enumerate(open("file")):
  3.     if num%2==0: even.append(line.strip())
  4.     elif num%2!=0: odd.append(line.strip())
  5. print odd   
  6. print even
  7.  
May 18 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: drew | last post by:
I am reading my textbook and doing the code examples in MS Visual C++ 6.0 for my next class beginning Jan 05. The textbook examples show line numbers. How do I get line numbers to show as I type in...
2
by: kak3012 | last post by:
Hi, I have a text file I will read it and write out binary. The file includes 256 coloums. I use while (infile.good()) { infile.getline (buffer,2200);
14
by: Vlad | last post by:
Please consider this code public class MyClass{ public bool MyMethod1(){ return false; } public bool MyMethod2(){ int x=0,y=1/x; return false; }
8
by: Arun Bhalla | last post by:
Hi, I'm developing an Explorer bar using VS.NET 2003 (C#) on Windows XP. For some time, I've noticed that I don't have filenames and line numbers appearing in my exceptions' stack traces. On...
10
by: Al | last post by:
Hi, I am seeking to obtain the line number of an error once deployed with out inserting line numbers in the method. The IDE inserts line numbers but this function does not appear to be a...
3
by: Jim Bancroft | last post by:
Hi all, In VB6 I used a 3rd party tool for line numbering my source code, to help with debugging. However, in experimenting with VB .Net I've noticed that my exceptions automatically provide...
2
by: Ben | last post by:
Hello all After years of playing developing stuff for fun and personal use I'm finally developing an app that I am intending to sell. As such, I'm trying to make it as reliable and stable as...
4
by: J L | last post by:
Are there any free add-ins for VB.Net that will add and remove line numbers from the source code? TIA John
7
by: Hulo | last post by:
In a C program I am required to enter three numbers (integers) e.g. 256 7 5 on execution of the program. C:\> 256 7 5 There should be spaces between the three numbers and on pressing "enter",...
3
by: Rahul | last post by:
Hi, Is there a way to get the line numbers to display in the exception when you have published your web site? Thanks Rahul
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.