Python File Operations

PythonPythonBeginner
Practice Now

Introduction

Welcome to the utopian future, where humanity has ascended to build sprawling metropolises across the stars. You are in Celestia, a cutting-edge space city orbiting around a distant exoplanet. As one of the leading architects of Celestia, you use advanced simulation software to design living spaces that are both functional and majestic.

Your goal for this lab is to harness the power of Python to develop a set of tools that will help manage the vast amount of architectural plans and documents. You aim to automate the tedious file operations that come with the upkeep of a space city's blueprints, contributing to the city's progress and efficiency.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python/FileHandlingGroup -.-> python/file_operations("`File Operations`") subgraph Lab Skills python/file_operations -.-> lab-271551{{"`Python File Operations`"}} end

Creating an Initial Blueprint File

In this step, you're going to set up the base of your new project by creating an initial file for your plans. This will be the foundation on which we build more complex file operations.

Let's write some basic information into this file using Python. Open a file write_plan.py in ~/project:

## write_plan.py
plan_content = """Celestia Oxygen Gardens Blueprint
Architect: [Your Name]
Last Updated: [Today's Date]
This space garden is designed to provide ample oxygen supply and recreational space to Celestia residents.
"""

with open('/home/labex/project/oxygen_gardens.txt', 'w') as file:
    file.write(plan_content)

Execute this script from your current working directory called ~/project:

python write_plan.py

Check the contents of the file with cat command:

cat /home/labex/project/oxygen_gardens.txt

You should see the content you wrote to the file displayed in the terminal:

Celestia Oxygen Gardens Blueprint
Architect: [Your Name]
Last Updated: [Today's Date]
This space garden is designed to provide ample oxygen supply and recreational space to Celestia residents.

Listing All Blueprint Files and Reading Contents

In this step, we will develop a script to list all blueprint files within the directory and then read a particular file's content.

Let’s assume you have multiple blueprint files in your directory by now. You'll open a list_blueprints.py script that lists all text files .txt present in the /home/labex/project/ directory.

## list_blueprints.py
import os

## Define the blueprints directory path
blueprints_dir = '/home/labex/project/'

## List all files in the directory
files = os.listdir(blueprints_dir)

## Filter out non-txt files and print the remaining files
print("Blueprint Files:")
for file in files:
    if file.endswith('.txt'):
        print(file)

## Assume 'oxygen_gardens.txt' is the file we want to read
file_to_read = 'oxygen_gardens.txt'
with open(os.path.join(blueprints_dir, file_to_read), 'r') as file:
    print(f"\nContents of {file_to_read}:")
    print(file.read())

Run the script from your terminal in the project directory:

python list_blueprints.py

The output should list all blueprint files followed by the content of oxygen_gardens.txt:

Blueprint Files:
oxygen_gardens.txt

Contents of oxygen_gardens.txt:
Celestia Oxygen Gardens Blueprint
Architect: [Your Name]
Last Updated: [Today's Date]
This space garden is designed to provide ample oxygen supply and recreational space to Celestia residents.

Summary

In this lab, you learned how to navigate, create, and manipulate files and directories using Python in a space-age setting. By automating these file operations, you've taken an important step towards building an efficient file management system for Celestia's architectural endeavors. The ability to handle file operations with Python is a valuable skill that can translate to a variety of real-world applications, and your journey through this lab has bolstered that ability.

Other Python Tutorials you may like