1. Introduction to the os Module¶
The os
module allows you to interact with the operating system, including file and directory manipulation.
In [1]:
import os
2. Working with File Paths¶
You can manipulate file paths and directories using functions from the os module.
In [2]:
import os
# Get the current working directory
cwd = os.getcwd()
print("Current working directory:", cwd)
# Join paths
path = os.path.join(cwd, "example.txt")
print("Full path to the file:", path)
# Split paths
directory, filename = os.path.split(path)
print("Directory:", directory)
print("Filename:", filename)
Current working directory: /Users/ssin4735/Documents/GitHub/GeoTools/FileHandling Full path to the file: /Users/ssin4735/Documents/GitHub/GeoTools/FileHandling/example.txt Directory: /Users/ssin4735/Documents/GitHub/GeoTools/FileHandling Filename: example.txt
3. Creating and Removing Directories¶
You can create and remove directories using os.makedirs()
and os.rmdir()
.
In [4]:
# Create a directory
os.makedirs("new_folder", exist_ok=True) # `exist_ok=True` prevents an error if the directory already exists
In [5]:
# Remove a directory
os.rmdir("new_folder") # This only works if the directory is empty
4. Listing Files in a Directory¶
You can list all files and directories within a directory using os.listdir()
.
In [7]:
# List all files and directories in the current directory
items = os.listdir(".")
print("Files and directories in current directory:", items)
Files and directories in current directory: ['Introduction_to_os_module.ipynb', 'Re_module.ipynb', '.ipynb_checkpoints']
5. Checking for File and Directory Existence¶
You can check if a file or directory exists using os.path.exists().
In [9]:
# Check if a file exists
file_exists = os.path.exists("example.txt")
print("File exists:", file_exists)
# Check if a directory exists
dir_exists = os.path.isdir("some_directory")
print("Directory exists:", dir_exists)
File exists: False Directory exists: False
In [13]:
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, world!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print("File content:", content)
File content: Hello, world!
7. Renaming and Removing Files¶
You can rename and remove files using os.rename() and os.remove().
Example:
In [11]:
# Rename a file
os.rename("example.txt", "renamed_example.txt")
# Remove a file
os.remove("renamed_example.txt")
In [14]:
import stat
# Change file permissions to read/write for owner, and read-only for others
os.chmod("example.txt", stat.S_IRUSR | stat.S_IWUSR | stat.S_IROTH)
9. Traversing Directories¶
You can traverse directories using os.walk(), which generates file names in a directory tree.
Example:
In [15]:
# Walk through directory tree
for root, dirs, files in os.walk("."):
print("Current directory:", root)
print("Subdirectories:", dirs)
print("Files:", files)
Current directory: . Subdirectories: ['.ipynb_checkpoints'] Files: ['Introduction_to_os_module.ipynb', 'example.txt', 'Re_module.ipynb'] Current directory: ./.ipynb_checkpoints Subdirectories: [] Files: ['Re_module-checkpoint.ipynb', 'Introduction_to_os_module-checkpoint.ipynb']
10. Environment Variables¶
You can access and modify environment variables using os.environ.
Example:
In [ ]:
# Get an environment variable
path = os.environ.get("PATH")
print("PATH environment variable:", path)
# Set an environment variable
os.environ["MY_VAR"] = "some_value"
print("MY_VAR:", os.environ.get("MY_VAR"))