Learn to perform basic file input/output (I/O) operations in Python, focusing on creating, writing, and reading text files. This lab will introduce you to managing data with files, a fundamental skill in programming.
Ensure that you are signed into your GitHub account
Join the GitHub Classroom and accept this assignment: Project 14 - Library System
Clone the repository to your computer using GitHub Desktop or open it online using Codespaces
Files are a way to store data on your disk, and Python provides built-in functions that make working with files straightforward. When you're programming, you'll often need to read data from files or write data to files, and Python's file handling capabilities are designed to handle these tasks efficiently.
To work with a file, you first need to open it using the open function.
You can open a file in several modes:
'r' for reading (default)
'w' for writing (creates a new file or truncates existing)
'a' for appending
'r+' for both reading and writing
Here's how you can open a file:
with open('example.txt', 'w') as file:
# The file is now open for writing
Once a file is opened in write mode, you can write text to it using the write() method:
with open('example.txt', 'w') as file:
file.write('Hello, world!')
To read the contents of a file, you need to open it in read mode.
with open('example.txt', 'r') as file:
content = file.read() # Reads the entire file contents
print(content)
Handling potential errors during file operations is crucial. Errors can occur for various reasons such as attempting to read a file that doesn't exist or encountering access permission issues. Python provides several built-in exceptions for handling file-related errors. The most common is FileNotFoundError, which occurs when a file that is attempted to be read doesn't exist.
try:
with open('example.txt', 'r') as file:
print(file.read())
except FileNotFoundError:
print("The file does not exist.")
Python’s file objects can be iterated over line by line using a simple for loop, which can be particularly useful for large files or when you need to process each line individually. This example reads one line at a time, prints it, and then moves on to the next.
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # strip() removes the newline character at the end of each line
Here is a simple To-Do List program that reads from and writes to a text file:
add_tasks_to_file: Opens the file in append mode to add new tasks at the end without deleting existing content, ensuring that each new task is written on a new line.
display_tasks: Opens the file in read mode to read tasks one by one, displaying them on the screen. It handles the possibility of the file not existing by catching errors and informing the user instead of crashing.
clear_tasks: Opens the file in write mode, which immediately clears all content from the file, leaving it completely empty.
Open lab1.py
Complete the music catalog manager program by programming the following functions:
add_song(): Open 'songs.txt' in append mode to add new song details entered by the user, formatting each entry as title, artist, album, and year followed by a newline.
list_songs(): Read and display each song from 'songs.txt', splitting song details by commas and printing in a readable format.
search_songs(): Prompt the user for a search term, read through 'songs.txt' to find matching entries, and display the details of each found song.
delete_song(): Ask for the song title to delete, read all songs from 'songs.txt', and rewrite only those that don't match the specified title back to the file.
Commit and push your code