Working with Files and Directories
File Management Operations (Copying, Moving, Deleting)
This topic focuses on file management operations in Python, specifically copying, moving, and deleting files. You'll learn how to perform these operations using the built-in functions and modules available in Python. This topic covers the essential techniques and considerations for managing files in your Python programs.
YouTube Video Link: File Management Operations in Python - Please note that the provided link is a placeholder. You can search for relevant videos on popular platforms like YouTube or other online learning platforms.
Examples
Example 1: Copying a File
import shutil
source = "path/to/source/file.txt"
destination = "path/to/destination/file.txt"
shutil.copy(source, destination)
Example 2: Moving a File
import shutil
source = "path/to/source/file.txt"
destination = "path/to/destination/file.txt"
shutil.move(source, destination)
Example 3: Deleting a File
import os
file_path = "path/to/file.txt"
os.remove(file_path)
Example 4: Copying a Directory
import shutil
source_dir = "path/to/source/dir"
destination_dir = "path/to/destination/dir"
shutil.copytree(source_dir, destination_dir)
Example 5: Moving a Directory
import shutil
source_dir = "path/to/source/dir"
destination_dir = "path/to/destination/dir"
shutil.move(source_dir, destination_dir)
Example 6: Deleting a Directory
import shutil
dir_path = "path/to/directory"
shutil.rmtree(dir_path)
Exercises
Exercise 1: Write a program that prompts the user to enter the path of a file and copies it to a specified destination folder.
Exercise 2:
Create a function called move_files
that takes a source directory and a destination directory as input. The function should move all files from the source directory to the destination directory.
Exercise 3: Write a program that asks the user to enter the path of a file and deletes it if it exists.
Exercise 4:
Create a function called copy_directory
that takes a source directory and a destination directory as input. The function should copy all files and subdirectories from the source directory to the destination directory.
Exercise 5: Write a program that prompts the user to enter the path of a directory and deletes it if it exists, along with all its files and subdirectories.
Navigating Directory Structures
This topic focuses on navigating directory structures in Python. It covers how to work with directories and paths, including listing directory contents, navigating through directories, and performing operations on files within directories. You'll learn how to use the built-in modules and functions in Python to efficiently navigate and manipulate directory structures.
YouTube Video Link: Navigating Directory Structures in Python - Please note that the provided link is a placeholder. You can search for relevant videos on popular platforms like YouTube or other online learning platforms.
Examples
Example 1: Listing Files in a Directory
import os
directory = "path/to/directory"
files = os.listdir(directory)
for file in files:
print(file)
Example 2: Checking if a Path is a Directory
import os
path = "path/to/directory"
if os.path.isdir(path):
print("Path is a directory.")
else:
print("Path is not a directory.")
Example 3: Navigating Through Directories
import os
current_directory = os.getcwd()
print("Current Directory:", current_directory)
os.chdir("path/to/new/directory")
new_directory = os.getcwd()
print("New Directory:", new_directory)
Example 4: Creating a Directory
import os
directory = "path/to/new/directory"
os.mkdir(directory)
Example 5: Removing a Directory
import os
directory = "path/to/directory"
os.rmdir(directory)
Exercises
Exercise 1: Write a program that prompts the user to enter a directory path and displays all the subdirectories and files within that directory.
Exercise 2:
Create a function called count_files
that takes a directory path as input and returns the total number of files in that directory and its subdirectories.
Exercise 3: Write a program that asks the user to enter a directory path and lists all the files (excluding directories) in that directory and its subdirectories.
Exercise 4:
Create a function called find_files
that takes a directory path and a file extension as input. The function should return a list of all the files in the directory and its subdirectories that have the specified file extension.
Exercise 5: Write a program that prompts the user to enter a directory path and displays the size (in bytes) of each file in the directory and its subdirectories.
Working with File Metadata (Permissions, Timestamps)
This topic focuses on working with file metadata in Python, specifically permissions and timestamps. You'll learn how to retrieve and modify the permissions of a file, as well as access and manipulate the various timestamps associated with a file, such as the creation time, modification time, and access time. Understanding and working with file metadata is essential for managing and tracking file properties in your Python programs.
YouTube Video Link: Working with File Metadata in Python - Please note that the provided link is a placeholder. You can search for relevant videos on popular platforms like YouTube or other online learning platforms.
Examples
Example 1: Retrieving File Permissions
import os
file_path = "path/to/file.txt"
permissions = os.stat(file_path).st_mode
print("Permissions:", oct(permissions))
Example 2: Modifying File Permissions
pythonCopy
import os
file_path = "path/to/file.txt"
# Set read, write, and execute permissions for the owner
os.chmod(file_path, 0o700)
Example 3: Retrieving File Timestamps
import os
import time
file_path = "path/to/file.txt"
# Get the modification timestamp
modification_timestamp = os.path.getmtime(file_path)
modification_time = time.ctime(modification_timestamp)
print("Modification Time:", modification_time)
Example 4: Modifying File Timestamps
import os
import time
file_path = "path/to/file.txt"
# Set the access and modification timestamps to the current time
current_time = time.time()
os.utime(file_path, (current_time, current_time))
Example 5: Checking if a File is Readable/Writable/Executable
pythonCopy
import os
file_path = "path/to/file.txt"
if os.access(file_path, os.R_OK):
print("File is readable.")
else:
print("File is not readable.")
Exercises
Exercise 1: Write a program that prompts the user to enter a file path and displays the permissions of the file in human-readable format (e.g., "readable", "writable", "executable") for the owner, group, and others.
Exercise 2:
Create a function called change_permissions
that takes a file path and a permission code as input. The function should modify the permissions of the file based on the provided permission code.
Exercise 3: Write a program that asks the user to enter a file path and displays the creation time, modification time, and access time of the file in a readable format.
Exercise 4:
Create a function called set_timestamp
that takes a file path, a timestamp type (e.g., "access", "modification"), and a timestamp value as input. The function should modify the respective timestamp of the file to the provided value.
Exercise 5: Write a program that prompts the user to enter a file path and checks if the file is executable.
Using the os and shutil modules
os
Module:The
os
module provides a way to interact with the operating system in a platform-independent manner.It includes functions for working with files, directories, and other operating system-related tasks.
Some commonly used functions from the
os
module are:os.getcwd()
: Returns the current working directory.os.listdir(path)
: Returns a list of files and directories in the specified path.os.path.join(path, *paths)
: Joins one or more path components intelligently.os.path.exists(path)
: Checks if a path exists.os.mkdir(path)
: Creates a new directory.os.remove(path)
: Removes a file.os.rename(src, dst)
: Renames a file or directory.os.chmod(path, mode)
: Changes the permissions of a file or directory.os.stat(path)
: Returns information about a file.
Example:
import os dir_path = os.getcwd() files = os.listdir(dir_path) for file in files: print(file)
shutil
Module:The
shutil
module provides high-level file operations and utilities.It simplifies tasks such as copying files and directories, moving files, and removing directories.
Some commonly used functions from the
shutil
module are:shutil.copy(src, dst)
: Copies a file from the source path to the destination path.shutil.copy2(src, dst)
: Copies a file and preserves its metadata (timestamps, permissions) in the destination.shutil.move(src, dst)
: Moves a file or directory from the source path to the destination path.shutil.rmtree(path)
: Removes a directory and all its contents.shutil.make_archive(base_name, format, root_dir)
: Creates an archive file (e.g., zip, tar) from a directory.
Example
import shutil source = "path/to/source/file.txt" destination = "path/to/destination/file.txt" shutil.copy(source, destination)
Last updated
Was this helpful?