Grouping Employees by Phone Number

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to group employees based on the last digit of their phone numbers and save the groups to separate CSV files. This project is designed to help you develop skills in file handling, data processing, and CSV file management using Python.

👀 Preview

## Input:
python group.py
ls
ls Groups
## Output:
Groups roster.csv group.py
Tail_num_0.csv  Tail_num_2.csv  Tail_num_4.csv  Tail_num_6.csv  Tail_num_8.csv
Tail_num_1.csv  Tail_num_3.csv  Tail_num_5.csv  Tail_num_7.csv  Tail_num_9.csv

🎯 Tasks

In this project, you will learn:

  • How to set up the project environment and prepare the necessary files
  • How to implement the logic to group employees based on the last digit of their phone numbers
  • How to save the grouped data to separate CSV files
  • How to verify the contents of the generated CSV files

🏆 Achievements

After completing this project, you will be able to:

  • Understand how to work with CSV files in Python
  • Develop skills in data processing and grouping
  • Demonstrate your ability to create and manage files and folders programmatically
  • Apply your Python programming knowledge to a real-world problem

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/FileHandlingGroup -.-> python/file_reading_writing("`Reading and Writing Files`") python/PythonStandardLibraryGroup -.-> python/os_system("`Operating System and System`") subgraph Lab Skills python/with_statement -.-> lab-302756{{"`Grouping Employees by Phone Number`"}} python/for_loops -.-> lab-302756{{"`Grouping Employees by Phone Number`"}} python/file_reading_writing -.-> lab-302756{{"`Grouping Employees by Phone Number`"}} python/os_system -.-> lab-302756{{"`Grouping Employees by Phone Number`"}} end

Implement the Grouping Logic

In this step, you will implement the logic to group the employees based on the last digit of their phone numbers and save the groups to separate CSV files.

  1. Open the group.py file in a text editor.
  2. Add the following code to the group() function:
import os
import csv

def group():
    """
    Group employees based on the last digit of their phone number and save each group to a separate CSV file.

    Reads employee data from a CSV file named 'roster.csv', groups them based on the last digit of their phone number,
    and saves each group to a separate CSV file in a folder named 'Groups'.

    The CSV file should have the following format:
    - The first row is the header row.
    - The remaining rows contain employee data, with each row representing a single employee.

    :return: None
    """
    ## Create the 'Groups' folder if it doesn't exist
    if not os.path.exists("Groups"):
        os.makedirs("Groups")

    ## Open the 'roster.csv' file for reading
    with open("roster.csv", "r") as file:
        reader = csv.reader(file)
        header = next(reader)  ## Read the header row of the CSV file

        ## Create a dictionary to store groups of employees based on their phone number's last digit
        groups = {}
        for row in reader:
            phone_number = row[1]  ## Get the phone number from the current row
            last_digit = int(phone_number[-1])  ## Extract the last digit of the phone number as an integer

            ## Append the current row to the corresponding group based on the last digit
            groups.setdefault(last_digit, []).append(row)

    ## Iterate over the groups and save each group to a separate CSV file
    for tail_num, employees in groups.items():
        filename = f"Groups/Tail_num_{tail_num}.csv"  ## Generate the filename for the current group
        with open(filename, "w", newline="") as file:
            writer = csv.writer(file)
            writer.writerow(header)  ## Write the header row to the CSV file
            writer.writerows(employees)  ## Write the employee data to the CSV file

if __name__ == "__main__":
    group()  ## Call the 'group' function to execute the grouping and saving process
  1. Save the group.py file.

Run the Grouping Script

In this step, you will run the group.py script to generate the grouped CSV files.

  1. Open a terminal and navigate to the /home/labex/project directory.
  2. Run the following command to execute the group.py script:
python group.py
  1. After the script finishes running, verify the creation of the Groups folder and the generated CSV files inside it.

Verify the Grouped CSV Files

In this step, you will verify the contents of the generated CSV files.

  1. Navigate to the Groups folder using the terminal.
  2. List the contents of the Groups folder using the ls command. You should see the following files:
Tail_num_0.csv  Tail_num_2.csv  Tail_num_4.csv  Tail_num_6.csv  Tail_num_8.csv
Tail_num_1.csv  Tail_num_3.csv  Tail_num_5.csv  Tail_num_7.csv  Tail_num_9.csv
  1. Open one of the CSV files (e.g., Tail_num_0.csv) and verify that the file contains the employee data, with the first row being the header and the remaining rows containing the employee information.

Congratulations! You have successfully completed the project of grouping employees based on the last digit of their phone numbers and saving the groups to separate CSV files.

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like