Free Coding Tutorials: Mastering Python Fundamentals – Part 7

Python Coding Bootcamps

Chapter 7: Files

Working with files, in this Mastering Python Fundamentals Chapter, is a crucial skill in programming. Python makes it easy to interact with files on your computer, whether you need to read, write, or manage them. In this chapter, we’ll explore how to handle files in Python, with step-by-step instructions and examples.

7.1 Directory and File Management

In Python, you can perform various operations on files and directories, such as creating, renaming, deleting, and navigating through directories.

7.1.1 Working with the os Module

The os module provides a way to interact with the operating system, allowing you to work with directories and files.

Example: Creating a Directory

import os

# Create a directory named 'my_folder'
os.mkdir('my_folder')

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as create_directory.py.
  4. Run the program by typing:
   python create_directory.py
  1. A new directory named my_folder will be created in your current directory.

Example: Listing Files in a Directory

import os

# List all files and directories in the current directory
items = os.listdir('.')
print(items)

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as list_directory.py.
  4. Run the program by typing:
   python list_directory.py
  1. The output will display a list of all files and directories in the current directory.

7.1.2 Renaming and Deleting Files

You can rename and delete files using the os module.

Example: Renaming a File

import os

# Rename a file from 'old_name.txt' to 'new_name.txt'
os.rename('old_name.txt', 'new_name.txt')

Step-by-Step Guide:

  1. Create a file named old_name.txt in your directory.
  2. Open your text editor.
  3. Type the code above into your editor.
  4. Save the file as rename_file.py.
  5. Run the program by typing:
   python rename_file.py
  1. The file old_name.txt will be renamed to new_name.txt.

Example: Deleting a File

import os

# Delete a file named 'my_file.txt'
os.remove('my_file.txt')

Step-by-Step Guide:

  1. Create a file named my_file.txt in your directory.
  2. Open your text editor.
  3. Type the code above into your editor.
  4. Save the file as delete_file.py.
  5. Run the program by typing:
   python delete_file.py
  1. The file my_file.txt will be deleted.

7.2 Reading and Writing Files

Python provides several built-in functions for reading from and writing to files. This section will cover the basics of file I/O (Input/Output).

7.2.1 Opening and Closing Files

Before you can read or write to a file, you need to open it. After performing operations, it’s important to close the file to free up resources.

Example: Opening and Closing a File

# Open a file in read mode
file = open('example.txt', 'r')

# Perform file operations...

# Close the file
file.close()

Step-by-Step Guide:

  1. Create a file named example.txt in your directory.
  2. Open your text editor.
  3. Type the code above into your editor.
  4. Save the file as open_close_file.py.
  5. Run the program by typing:
   python open_close_file.py

7.2.2 Reading Files

You can read the contents of a file using methods like read(), readline(), or readlines().

Example: Reading the Entire File

# Open a file in read mode
file = open('example.txt', 'r')

# Read the entire file
content = file.read()
print(content)

# Close the file
file.close()

Step-by-Step Guide:

  1. Add some text content to the example.txt file.
  2. Open your text editor.
  3. Type the code above into your editor.
  4. Save the file as read_file.py.
  5. Run the program by typing:
   python read_file.py
  1. The content of example.txt will be printed to the console.

Example: Reading File Line by Line

# Open a file in read mode
file = open('example.txt', 'r')

# Read each line one by one
for line in file:
    print(line, end='')

# Close the file
file.close()

Step-by-Step Guide:

  1. Ensure example.txt has multiple lines of text.
  2. Open your text editor.
  3. Type the code above into your editor.
  4. Save the file as read_lines.py.
  5. Run the program by typing:
   python read_lines.py
  1. Each line of the file will be printed to the console.

7.2.3 Writing to Files

To write data to a file, you can use the write() method. If the file does not exist, Python will create it.

Example: Writing to a File

# Open a file in write mode
file = open('output.txt', 'w')

# Write some text to the file
file.write('Hello, Python!')

# Close the file
file.close()

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as write_file.py.
  4. Run the program by typing:
   python write_file.py
  1. A new file named output.txt will be created, containing the text Hello, Python!.

Example: Appending to a File

# Open a file in append mode
file = open('output.txt', 'a')

# Append some text to the file
file.write('nWelcome to file handling in Python.')

# Close the file
file.close()

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as append_file.py.
  4. Run the program by typing:
   python append_file.py
  1. The text Welcome to file handling in Python. will be appended to output.txt.

7.3 CSV: Reading and Writing CSV Files

CSV (Comma-Separated Values) files are a common format for storing tabular data. Python’s csv module makes it easy to work with CSV files.

7.3.1 Reading CSV Files

You can read a CSV file using the csv.reader object.

Example: Reading a CSV File

import csv

# Open the CSV file
with open('data.csv', 'r') as file:
    reader = csv.reader(file)

    # Iterate over each row in the CSV
    for row in reader:
        print(row)

Step-by-Step Guide:

  1. Create a CSV file named data.csv with some sample data.
  2. Open your text editor.
  3. Type the code above into your editor.
  4. Save the file as read_csv.py.
  5. Run the program by typing:
   python read_csv.py
  1. Each row in data.csv will be printed to the console.

7.3.2 Writing to CSV Files

You can write data to a CSV file using the csv.writer object.

Example: Writing to a CSV File

import csv

# Open the CSV file
with open('output.csv', 'w', newline='') as file:
    writer = csv.writer(file)

    # Write a row of data
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['Alice', '23', 'New York'])
    writer.writerow(['Bob', '30', 'San Francisco'])

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as write_csv.py.
  4. Run the program by typing:
   python write_csv.py
  1. A new CSV file named output.csv will be created with the specified data.

7.4 Exception Handling

When working with files, you may encounter errors, such as a file not being found. Python provides ways to handle these exceptions gracefully.

7.4.1 Handling File Exceptions

You can handle exceptions using the try...except block.

Example: Handling File Not Found Error

try:
    # Attempt to open a file that doesn't exist
    file = open('non_existent_file.txt', 'r')
except FileNotFoundError:
    print("File not found. Please check the file name.")

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as file_exception.py.
  4. Run the program by typing:
   python file_exception.py
  1. The output will display File not found. Please check the file name.

Handling files in Python is essential for managing data in various formats. By mastering file operations, you can read, write, and manipulate files, enabling you to build more complex and data-driven applications.

Latest Posts