-2

I am a beginner in Python self studying Python 2.7. May I ask one question I got in line counting codes in Python? How do I intuitively understand why the below works, especially how I can understand what the for loop is doing with the file handle?

Many thanks all

fhand=open('test.txt')
count=0
for line in fhand:
    count=count+1

print count
Larry
  • 9
  • 2

4 Answers4

2

open() returns a file object.

count=0 initializes a count variable with the value of 0.

As you can see in the documentation of the file object, using a for loop will get you the contents of the file line-by-line. (This is because file objects are iterable.)

Each time you get the contents of a line, count=count+1 adds 1 to the count variable.

print count dumps the contents of the count variable.

Community
  • 1
  • 1
Sam
  • 18,756
  • 2
  • 40
  • 65
0

A file object is an iterator which when used will return each line of the file. Therefore, the count in the for-loop will simply count the number of lines in the file

smac89
  • 26,360
  • 11
  • 91
  • 124
0
fhand=open('test.txt') # Opens the file and puts the content of it in the "fhand" variable
count=0 # Creates new variable "count" and sets it to 0
for line in fhand:
    count=count+1 # Increase count by 1 for every line in the file

print count # Prints the amount of lines
Tropic
  • 127
  • 4
  • 6
0

In Python, when you open the file, you are getting access to its contents.

fhand=open('test.txt')

The above does the job.

count=0

When you initialize count to 0, that means the variable is set to value 0, and once it enters the loop,

count=count+1

adds +1 to it every time.

for line in fhand

Above code is for iteration. It loops over each and every line of the file fhand and for every iteration, it adds +1 to count.

When the iteration is complete, the value of count is set, which you print later to get the count of number of lines.

xCodeZone
  • 184
  • 10