0
0
Pythonprogramming~15 mins

File path handling in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
File path handling
📖 Scenario: You are organizing files on your computer. You want to work with file paths to find out folder names and file names easily.
🎯 Goal: You will create a program that uses file path handling to extract folder names and file names from a given path.
📋 What You'll Learn
Create a variable with a file path string
Create a variable to hold the folder name from the path
Create a variable to hold the file name from the path
Print the folder name and file name
💡 Why This Matters
🌍 Real World
File path handling is useful when working with files on your computer, like organizing documents or reading data files.
💼 Career
Many programming jobs require working with file paths to read, write, or organize files correctly across different operating systems.
Progress0 / 4 steps
1
Create the file path variable
Create a variable called file_path and set it to the string "/home/user/documents/report.txt".
Python
Need a hint?

Use quotes around the path string exactly as shown.

2
Import pathlib and create folder name variable
Import the Path class from the pathlib module. Then create a variable called folder_name that gets the parent folder of file_path using Path(file_path).parent.
Python
Need a hint?

Use from pathlib import Path to import. Use Path(file_path).parent to get the folder.

3
Create file name variable
Create a variable called file_name that gets the file name from file_path using Path(file_path).name.
Python
Need a hint?

Use Path(file_path).name to get the file name.

4
Print folder name and file name
Print the folder_name and file_name variables on separate lines using two print statements.
Python
Need a hint?

Use two print statements: print(folder_name) and print(file_name).