In this challenge we are going to focus on accessing a text file in Python to read the content of the file line by line.
Your first challenge consists of writing a Python script that will read the following text file, one line at a time and display the content of each line on screen.
To read the content of a text file line by line we are going to use a for loop that will loop through and extract each line of the text file one at a time. It will stop looping only once the it will have reached the last line.
Check this animation that explains this process:
When the text file uses a CSV format (Comma Separtred Values), each line contains several values separated using a special character, often a comma or a semi-colon. In this case we can use the split() method to extract each value of each line and store them in a list.
Check this animation that explains this process further:
The solutions below contains 5 main steps:
- Step 1: Open the text file using the open() function. This function takes two parameters: The name of the file (e.g. “playlist.txt”) and the access mode. In our case we are opening the file in read-only mode: “r”.
- Read through the file one line at a time using a for loop.
- Split the line into an array. This is because in this file each value is separated with a semi-column. By splitting the line we can then easily access each value (field) individually.
- Output the content of each field using the print method.
- Once the for loop is completed, close the file using the close() method.
Main Access Modes when opening a file with the open() function.
|r||Opens a file in read only mode. This is the default mode.|
|r+||Opens a file for both reading and writing.|
|w||Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.|
|w+||Opens a file for both writing and reading. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.|
|a||Opens a file for appending. The file pointer is at the end of the file. So new data will be added at the end of the file. If the file does not exist, it creates a new file for writing.|
|a+||Opens a file for both appending and reading. The file pointer is at the end of the file. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.|
Use what you have learnt in this blogbpost to complete these challenges:
My mp3 playlist(Reading a text file using Python) US Population(Reading a text file using Python)