Python Utility Functions for File Handling, Time Management, and Path Operations

  • Share this:

Code introduction


This code collection includes a series of functions using Python's built-in libraries, covering file reading, writing, path searching, time handling, sleep, path checking, and JSON operations.


Technology Stack : os, sys, re, json, datetime, time

Code Type : Code collection

Code Difficulty : Intermediate


                
                    
import os
import sys
import re
import json
import datetime
import time

def read_file(file_path):
    with open(file_path, 'r') as file:
        return file.read()

def write_file(file_path, content):
    with open(file_path, 'w') as file:
        file.write(content)

def find_files(start_path, file_pattern):
    matches = []
    for root, dirs, files in os.walk(start_path):
        for file in files:
            if re.match(file_pattern, file):
                matches.append(os.path.join(root, file))
    return matches

def get_current_time():
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def sleep_seconds(seconds):
    time.sleep(seconds)

def is_directory(path):
    return os.path.isdir(path)

def is_file(path):
    return os.path.isfile(path)

def read_json(file_path):
    with open(file_path, 'r') as file:
        return json.load(file)

def write_json(file_path, data):
    with open(file_path, 'w') as file:
        json.dump(data, file, indent=4)