Python3 open and read files

Can you explain what is going on in this code? I do not seem to understand how you can open a file and read it in turn instead of all 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 
+6
source share
2 answers

Magic:

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

Python file objects are special in that they can be repeated in a for loop. At each iteration, it extracts the next line of the file. Since it includes the last character in a line, which may be a new line, it is often useful to check and delete the last character.

+7
source

As Moshe wrote, objects of open files can be iterated. Only they are not of type file in Python 3.x (as in Python 2.x). If a file object opens in text mode, the iteration unit is a single text line containing \n .

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

If you want to immediately read the contents of the file (in a multi-line line), you can use content = f.read() .

There is a minor error in the code. An open file must always be closed. I mean use f.close() after the for loop. Or you can wrap an open with construct that closes the file for you - I suggest getting used to a later approach.

+7
source

All Articles