Sample Exercises - Check back soon for more!
Lux Labz Training Exercises
Filename | Action |
---|---|
exercise_001.md | Preview |
exercise_002.md | Preview |
exercise_02.md | Preview |
Preview: exercise_002.md
Intermediate Python Training Exercise: File Handling and Data Processing
Overview
In this exercise, you will work on intermediate-level Python skills by handling file input/output and processing data. You will create a Python script that reads data from a CSV file, processes it, and writes the results to a new file. This exercise will help you practice working with file operations and basic data processing techniques.
Prerequisites
- Basic understanding of Python syntax
- Familiarity with data types (lists, dictionaries)
- Basic knowledge of CSV files and how to handle them in Python
Exercise Steps
Step 1: Setup
- Create a CSV file named
data.csv
with the following content:Name,Age,Occupation Alice,30,Engineer Bob,25,Data Scientist Charlie,35,Teacher
- Create a new Python script file named
process_data.py
in the same directory asdata.csv
.
Step 2: Read the CSV File
Import the necessary module for handling CSV files:
import csv
Open and read the CSV file:
with open('data.csv', mode='r') as file: reader = csv.DictReader(file) data = list(reader)
Print the data to verify it has been read correctly:
print(data)
Step 3: Process the Data
Create a new list to store processed data:
processed_data = []
Process each row to add a new field
Senior
that isTrue
ifAge
is greater than or equal to 30, otherwiseFalse
:for row in data: row['Senior'] = int(row['Age']) >= 30 processed_data.append(row)
Step 4: Write Data to a New CSV File
Specify the fieldnames including the new
Senior
field:fieldnames = ['Name', 'Age', 'Occupation', 'Senior']
Write the processed data to a new CSV file named
processed_data.csv
:with open('processed_data.csv', mode='w', newline='') as file: writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerows(processed_data)
Verify the new CSV file has been created and contains the correct data by opening
processed_data.csv
.
Step 5: Testing and Verification
- Run your Python script to ensure it completes without errors and creates the
processed_data.csv
file. - Check the contents of
processed_data.csv
to verify that each person’sSenior
status has been correctly calculated and recorded.
Conclusion
Congratulations on completing this intermediate-level exercise! You have successfully read, processed, and written data using Python's CSV handling capabilities. This exercise will help you better understand file operations and data processing in Python.
Feel free to modify the CSV file and script to practice with different datasets and processing tasks!