Uso del Módulo os para Manipulación de Archivos y Directorios

El módulo os (Operating System) proporciona una forma de interactuar con el sistema operativo. Es muy útil para tareas como crear, eliminar, renombrar archivos y directorios, verificar su existencia, y obtener información sobre ellos.

import os

# --- Current Directory ---
print(f"Current working directory: {os.getcwd()}")

# --- Creating and Removing Directories ---
new_directory = "my_new_folder"
if not os.path.exists(new_directory):
    os.makedirs(new_directory) # Creates directory and any necessary intermediate directories
    print(f"Directory '{new_directory}' created.")
else:
    print(f"Directory '{new_directory}' already exists.")

# Creating a file inside the new directory
file_in_folder = os.path.join(new_directory, "data.txt")
with open(file_in_folder, 'w') as f:
    f.write("This is some data.")
print(f"File '{file_in_folder}' created.")

# List contents of a directory
print(f"Contents of '{os.getcwd()}': {os.listdir('.')}") # '.' refers to current directory
print(f"Contents of '{new_directory}': {os.listdir(new_directory)}")

# Renaming a file
old_file_name = file_in_folder
new_file_name = os.path.join(new_directory, "renamed_data.txt")
os.rename(old_file_name, new_file_name)
print(f"File renamed from '{old_file_name}' to '{new_file_name}'.")

# Renaming a directory
old_dir_name = new_directory
new_dir_name = "my_renamed_folder"
os.rename(old_dir_name, new_dir_name)
print(f"Directory renamed from '{old_dir_name}' to '{new_dir_name}'.")

# Getting file/directory information
if os.path.exists(new_dir_name):
    print(f"Is '{new_dir_name}' a directory? {os.path.isdir(new_dir_name)}")
    print(f"Is '{new_dir_name}' a file? {os.path.isfile(new_dir_name)}")
    # To get info about the file inside
    file_path = os.path.join(new_dir_name, "renamed_data.txt")
    if os.path.exists(file_path):
        file_stats = os.stat(file_path)
        print(f"File size of '{file_path}': {file_stats.st_size} bytes")
        print(f"Last modification time (timestamp): {file_stats.st_mtime}")

# Deleting a file
file_to_delete = os.path.join(new_dir_name, "renamed_data.txt")
if os.path.exists(file_to_delete):
    os.remove(file_to_delete)
    print(f"File '{file_to_delete}' deleted.")

# Deleting an empty directory
if os.path.exists(new_dir_name) and not os.listdir(new_dir_name): # Check if empty
    os.rmdir(new_dir_name)
    print(f"Directory '{new_dir_name}' deleted.")
else:
    print(f"Directory '{new_dir_name}' is not empty or does not exist, cannot delete with rmdir.")

# If you need to remove a non-empty directory and its contents, use shutil.rmtree
import shutil
if not os.path.exists("folder_to_remove"):
    os.makedirs("folder_to_remove/subfolder")
    with open("folder_to_remove/subfolder/test.txt", "w") as f:
        f.write("temp content")
    print("Created 'folder_to_remove' for shutil.rmtree example.")

if os.path.exists("folder_to_remove"):
    shutil.rmtree("folder_to_remove")
    print("Directory 'folder_to_remove' and its contents removed using shutil.rmtree.")