How to create a filesystem node using Python?

A filesystem node represents any entity in the file system, such as files, directories, or symbolic links. Python provides powerful modules like os and pathlib to create and manipulate these filesystem nodes programmatically.

Filesystem nodes have attributes like names, sizes, permissions, and timestamps. You can create, rename, delete, and navigate through them to perform operations like reading files, creating directories, and checking properties.

Creating Directories

Using os.mkdir()

The os.mkdir() function creates a single directory ?

import os

# Create a single directory
directory_path = "new_directory"
os.mkdir(directory_path)
print(f"Directory '{directory_path}' created successfully!")
Directory 'new_directory' created successfully!

Using os.makedirs() for Nested Directories

The os.makedirs() function creates nested directories if parent directories don't exist ?

import os

# Create nested directories with error handling
directory_path = "parent/child/grandchild"

try:
    os.makedirs(directory_path)
    print("Nested directories created successfully!")
except FileExistsError:
    print("Directory already exists!")
except OSError as e:
    print(f"Directory creation failed: {e}")
Nested directories created successfully!

Creating Files

Basic File Creation

Use the open() function with write mode to create a file ?

import os

# Create a file with content
file_path = "sample.txt"

try:
    with open(file_path, "w") as file:
        file.write("Hello, world!")
    print("File created successfully!")
except OSError as e:
    print(f"File creation failed: {e}")
File created successfully!

Creating Files with Existence Check

Check if a file exists before creating it to avoid overwriting ?

import os

file_path = "example.txt"

# Check if file exists before creating
if not os.path.exists(file_path):
    try:
        with open(file_path, "w") as file:
            file.write("This is a new file.")
        print("File created successfully!")
    except OSError as e:
        print(f"File creation failed: {e}")
else:
    print("File already exists!")
File created successfully!

Verification and Path Operations

Always verify that filesystem nodes were created successfully ?

import os

# Create directory and file, then verify
directory_path = "test_dir"
file_path = os.path.join(directory_path, "test_file.txt")

# Create directory
os.makedirs(directory_path, exist_ok=True)

# Create file inside directory
with open(file_path, "w") as file:
    file.write("Test content")

# Verify creation
if os.path.exists(directory_path):
    print("Directory created successfully!")
    
if os.path.exists(file_path):
    print("File created successfully!")
    print(f"File size: {os.path.getsize(file_path)} bytes")
Directory created successfully!
File created successfully!
File size: 12 bytes

Best Practices

Function Purpose Best For
os.mkdir() Single directory Creating one directory level
os.makedirs() Nested directories Creating directory hierarchies
open() with with File creation Safe file handling
os.path.exists() Check existence Avoiding overwrites

Conclusion

Use os.makedirs() for creating directories with proper error handling. Always use with statements for file operations to ensure proper resource management. Verify filesystem node creation using os.path.exists().

Updated on: 2026-03-24T18:12:16+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements