Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 opening files and reading lines

Tags:

python-3.x

Can you explain what is going on in this code? I don't seem to understand how you can open the file and read it line by line instead of all of the sentences at the same time in a for loop. Thanks

Let's say I have these sentences in a document file:

cat:dog:mice
cat1:dog1:mice1
cat2:dog2:mice2
cat3:dog3:mice3

Here is the code:

from sys import argv

filename = input("Please enter the name of a file: ")
f = open(filename,'r')

d1ct = dict()
print("Number of times each animal visited each station:")
print("Animal Id           Station 1           Station 2")

for line in f:
     if '\n' == line[-1]:
          line = line[:-1]
     (AnimalId, Timestamp, StationId,) = line.split(':')
     key = (AnimalId,StationId,)
     if key not in d1ct:
          d1ct[key] = 0
     d1ct[key] += 1
like image 234
user1730308 Avatar asked Nov 13 '12 02:11

user1730308


2 Answers

The magic is at:

for line in f:
     if '\n' == line[-1]:
          line = line[:-1]

Python file objects are special in that they can be iterated over in a for loop. On each iteration, it retrieves the next line of the file. Because it includes the last character in the line, which could be a newline, it's often useful to check and remove the last character.

like image 184
Moshe Avatar answered Sep 24 '22 21:09

Moshe


As Moshe wrote, open file objects can be iterated. Only, they are not of the file type in Python 3.x (as they were in Python 2.x). If the file object is opened in text mode, then the unit of iteration is one text line including the \n.

You can use line = line.rstrip() to remove the \n plus the trailing withespaces.

If you want to read the content of the file at once (into a multiline string), you can use content = f.read().

There is a minor bug in the code. The open file should always be closed. I means to use f.close() after the for loop. Or you can wrap the open to the newer with construct that will close the file for you -- I suggest to get used to the later approach.

like image 33
pepr Avatar answered Sep 21 '22 21:09

pepr