SIC7 - Stage 1: File Handling & CSV

3 min read 3 hours ago
Published on Sep 06, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial covers the basics of file handling and working with CSV (Comma-Separated Values) files, as demonstrated in the video from the Samsung Innovation Campus. You'll learn how to read, write, and manipulate CSV files using Python, which is essential for data management and analysis in various applications.

Step 1: Setting Up Your Environment

Before diving into file handling, ensure you have the necessary tools to work with CSV files.

  1. Install Python: If you haven't already, download and install Python from the official website.
  2. Choose an IDE: Use an Integrated Development Environment (IDE) like PyCharm, Visual Studio Code, or Jupyter Notebook for writing your code.
  3. Familiarize with CSV Module: Python's built-in csv module will be used for handling CSV files.

Step 2: Creating a CSV File

Start by creating a simple CSV file that you can manipulate.

  1. Open a Text Editor: Use any text editor (like Notepad or VS Code).
  2. Write Data: Input data in the following format:
    Name, Age, City
    John, 25, New York
    Alice, 30, Los Angeles
    Bob, 22, Chicago
    
  3. Save the File: Save the file as data.csv.

Step 3: Reading a CSV File

Learn how to read the contents of the CSV file you just created.

  1. Import the CSV Module:
    import csv
    
  2. Open the CSV File:
    with open('data.csv', mode='r') as file:
    
  3. Read the File:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        print(row)
    
    • This code will print each row of the CSV file.

Step 4: Writing to a CSV File

Next, learn how to write new data into a CSV file.

  1. Open the CSV File in Write Mode:
    with open('new_data.csv', mode='w', newline='') as file:
    
  2. Create a CSV Writer:
    csv_writer = csv.writer(file)
    
  3. Write Header and Data:
    csv_writer.writerow(['Name', 'Age', 'City'])
    csv_writer.writerow(['Tom', 28, 'Boston'])
    
    • This will create a new CSV file called new_data.csv with the specified data.

Step 5: Appending Data to a CSV File

To add more data to an existing CSV file without overwriting it, follow these steps.

  1. Open the CSV File in Append Mode:
    with open('data.csv', mode='a', newline='') as file:
    
  2. Create a CSV Writer:
    csv_writer = csv.writer(file)
    
  3. Append New Data:
    csv_writer.writerow(['Lisa', 27, 'San Francisco'])
    

Conclusion

You have now learned the essentials of file handling and CSV manipulation using Python. You can create, read, write, and append data to CSV files, which is crucial for managing datasets in your projects. Next steps could involve exploring more advanced data analysis libraries like Pandas, which can simplify working with CSV files even further.