Python Reading and Writing Files

PythonPythonBeginner
Practice Now

Introduction

In the frosty expanse of the Ice Kingdom, a talented ice sculptor named Alaric is facing a unique challenge. Known for his incredible ability to bring ice to life through his sculptures, Alaric needs to catalogue his latest collection of artworks before the upcoming Ice Art Expo. However, there's a catch! Alaric wants to digitize his catalogue, and he has decided to learn programming with Python to achieve this task.

Join Alaric in his icy studio as he learns how to use Python for reading from and writing to files. Your objective is to help him create a digital portfolio that he can proudly present at the Expo.

Immerse yourself in this enchanting scenario, where every keystroke chisels away at the data, crafting a masterpiece of information. Get ready to help Alaric use Python to etch his art into the annals of digital history.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python/FileHandlingGroup -.-> python/file_reading_writing("`Reading and Writing Files`") subgraph Lab Skills python/file_reading_writing -.-> lab-271552{{"`Python Reading and Writing Files`"}} end

Creating the Catalogue File

In this step, you will help Alaric set up a new text file to store his ice sculpture catalogue. We'll start by creating a Python script that will create or open a file where Alaric's sculptures will be listed.

  1. Write the Python code below in the /home/labex/project/create_catalogue.py file and save it:
## create_catalogue.py
filename = '/home/labex/project/sculpture_catalogue.txt'

## Using 'a' to append to the file if it exists or create a new one if it doesn't
with open(filename, 'a') as file:
      pass  ## This will create an empty file if it doesn't exist

print(f"Catalogue file '{filename}' is ready.")
  1. Run the script using Python:
python3 ~/project/create_catalogue.py

You should see the output confirming the catalogue file is ready:

Catalogue file '/home/labex/project/sculpture_catalogue.txt' is ready.

Writing Sculpture Entries into the Catalogue

Now that Alaric has his catalogue file ready, it's time to add some entries. We'll write a Python function to include a new sculpture each time he finishes one.

  1. Open a script called add_sculpture.py in ~/project:
## add_sculpture.py
def add_sculpture(name, artist, date, material, catalogue_file='sculpture_catalogue.txt'):
      entry = f"{name}, Created by {artist}, Date: {date}, Material: {material}\n"
      with open(catalogue_file, 'a') as file:
         file.write(entry)

## Example usage:
add_sculpture('Frozen Swan', 'Alaric', '2023-01-15', 'Ice')
  1. Have Alaric add the 'Frozen Swan' entry by running the script:
python3 ~/project/add_sculpture.py

To confirm that the entry has been added, you can check the file contents using cat command:

cat ~/project/sculpture_catalogue.txt

You should see the 'Frozen Swan' entry in the sculpture_catalogue.txt:

Frozen Swan, Created by Alaric, Date: 2023-01-15, Material: Ice

Reading from the Catalogue

For the final step, Alaric wants to be able to review all his sculptures in the catalogue. You'll implement a function to read from the file and print each entry to the console.

  1. Open a script called read_catalogue.py in ~/project.
  2. Write a Python function to read the entries from the catalogue:
## read_catalogue.py
def read_catalogue(catalogue_file='sculpture_catalogue.txt'):
      with open(catalogue_file, 'r') as file:
         for line in file:
            print(line.strip())

## Call the function to read and print the catalogue
read_catalogue()
  1. Run the script using Python to display the catalogue in the terminal:
python3 ~/project/read_catalogue.py

Alaric should be able to see all of his sculptures displayed on the console:

Frozen Swan, Created by Alaric, Date: 2023-01-15, Material: Ice

Summary

In this lab, we ventured into the enchanting Ice Kingdom to assist the renowned ice sculptor Alaric in digitizing his precious artwork catalogue. We learned how to create, write to, and read from text files in Python - essential skills for any programmer venturing through the realms of data.

This hands-on experience not only bolstered our file manipulation abilities but also etched into our memory the delight of sculpting digital data in the shape of usable and informative Python scripts.

May this journey serve as a pillar of knowledge in your coding archive, standing stoically like one of Alaric's immortal ice sculptures. With these skills, your ability to handle file I/O in Python should be as crystalline as the sculptures themselves.

Other Python Tutorials you may like