Kickstart 2020 with new opportunities! - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
2. Reading text files in Python
Summary

Instruction

Let's do a quick recap first – a simple example where we print the contents of a CSV file without any parsing. Take a look:

with open('departments.csv') as csv_file:
for row in csv_file:
print(row)


The with syntax is a convenient way of opening files in Python, since it will close the file for us when we no longer need it. The open() function is used to open a text file. The default mode when you open a file is "reading". Once we've opened the file, we can create a for loop and print the file line by line.

Note: when you open() a file in a program, you won't actually see the file. The open() function locates the file on your computer and assigns to it a unique number within the context of the program. (You don't need to understand the details of this process).

Exercise

Load the people.csv file, and print its contents line by line. Add the following prefixes to all lines:

Line 1: {line1}
Line 2: {line2}
...


Stuck? Here's a hint!

Use the code from the explanation. Add a counter variable and increase its value inside the loop.