SIC7 - Stage 1: File Handling & CSV
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.
- Install Python: If you haven't already, download and install Python from the official website.
- Choose an IDE: Use an Integrated Development Environment (IDE) like PyCharm, Visual Studio Code, or Jupyter Notebook for writing your code.
- 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.
- Open a Text Editor: Use any text editor (like Notepad or VS Code).
- Write Data: Input data in the following format:
Name, Age, City John, 25, New York Alice, 30, Los Angeles Bob, 22, Chicago
- 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.
- Import the CSV Module:
import csv
- Open the CSV File:
with open('data.csv', mode='r') as file:
- 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.
- Open the CSV File in Write Mode:
with open('new_data.csv', mode='w', newline='') as file:
- Create a CSV Writer:
csv_writer = csv.writer(file)
- 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.
- This will create a new CSV file called
Step 5: Appending Data to a CSV File
To add more data to an existing CSV file without overwriting it, follow these steps.
- Open the CSV File in Append Mode:
with open('data.csv', mode='a', newline='') as file:
- Create a CSV Writer:
csv_writer = csv.writer(file)
- 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.