How to count lines in a text file ?

Brian van den Broek bvande at po-box.mcgill.ca
Mon Sep 20 13:03:30 EDT 2004


Ling Lee said unto the world upon 2004-09-20 09:36:
> Thanks for you replies :)
> 
> I just ran the program with a different file name, and it only counts the 
> number of lines in the file named test.txt. I try to give it a nother try 
> with your input...
> 
> Thanks again... for the fast reply... Hope I get it right this time :)
> 
> 

<SNIP>

>>On Mon, Sep 20, 2004 at 03:18:53PM +0200, Ling Lee wrote:
>>
>>>Hi all.
>>>
>>>I'm trying to write a program that:
>>>1) Ask me what file I want to count number of lines in, and then counts 
>>>the
>>>lines and writes the answear out.
>>>
>>>2) I made the first part like this:
>>>
>>>in_file = raw_input("What is the name of the file you want to open: ")
>>>in_file = open("test.txt","r")
>>>text = in_file.read()
>>>
>>>3) I think that I have to use a for loop ( something like: for line in 
>>>text:
>>>count +=1)
>>>Or maybee I have to do create a def: something like: ( def loop(line,
>>>count)), but not sure how to do this properly.
>>>And then perhaps use the readlines() function, but again not quite sure 
>>>how
>>>to do this. So do one of you have a good idea.
>>>
>>>Thanks for all help 

Hi Ling Lee,

you've got:

in_file = raw_input("What is the name of the file you want to open: ")
in_file = open("test.txt","r")

What this does is take the user input and assign it the name "in_file" 
and then promptly reassigns the name "in_file" to the output of 
open("test.txt","r").

So, you never make use of the input, and keep asking it to open test.txt 
instead.

Try something like:

in_file_name = raw_input("What is the file you want to open: ")
in_file = open(in_file_name,"r")

Also, and I say this as a fellow newbie, you might want to check out the 
Tutor list: <http://mail.python.org/pipermail/tutor/>

HTH,

Brian vdB




More information about the Python-list mailing list