Python Directory and Files Management
1. Getting Current Working Directory
import os
current_dir = os.getcwd()
print(current_dir)Returns the directory from which the Python script is executed.
2. Changing the Working Directory
import os
os.chdir("C:/Projects")
print(os.getcwd())Changes the active working directory for file operations.
3. Listing Files and Directories
import os
items = os.listdir(".")
print(items)Returns all files and folders in the specified directory.
4. Creating a Directory
mkdir()creates a single directorymakedirs()creates nested directories
5. Checking File or Directory Existence
Essential for safe file operations.
6. Creating and Writing to a File
Creates the file if it does not exist and writes content.
7. Reading from a File
Reads the entire content of the file into a string.
8. Renaming and Deleting Files
Used to manage file lifecycle.
9. Copying and Moving Files
Provides advanced file handling capabilities.
10. Modern File Handling with pathlib
pathlib offers an object-oriented and cleaner approach for file and directory manipulation.
Last updated