DEV Community

Cover image for Simplifying Your Daily Routine with Handy Python Snippets
MK
MK

Posted on • Originally published at webdesignguy.me on

Simplifying Your Daily Routine with Handy Python Snippets

Python, known for its simplicity and power, is the go-to language for many when it comes to automating mundane tasks. Its like having a digital Swiss Army knife at your fingertips! Today, Im excited to share three Python snippets that have made my life easier. I hope they do the same for you!

Tidy Up Your Files: Python for Easy File Renaming

Have you ever been swamped with files that needed their extensions changed? Maybe youve downloaded a batch of files as .txt and need them as .md for your Markdown editor. Heres a Python script that does just the renaming for you:


import os

def rename_files_in_directory(directory, old_extension, new_extension):
    # Loop through all the files in the specified directory
    for filename in os.listdir(directory):
        # Check if the file ends with the old extension
        if filename.endswith(old_extension):
            # Create the new filename by replacing the old extension with the new one
            new_filename = filename.replace(old_extension, new_extension)
            # Rename the file
            os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))
            print(f"Renamed {filename} to {new_filename}")

# Example usage: rename all .txt files to .md in the specified directory
rename_files_in_directory('your_directory_path', '.txt', '.md')

Enter fullscreen mode Exit fullscreen mode

This snippet is a lifesaver when youre dealing with large numbers of files. Just specify the directory and the extensions, and watch the magic happen!

Unearth Hidden Links: Extract URLs from Text

As someone who works with a lot of text data, I often find myself needing to extract URLs from blocks of text. Whether its for data analysis or just to keep track of interesting links, this snippet comes in handy:


import re

def extract_urls(text):
    # Regular expression for finding URLs
    url_regex = r'https?://\S+'
    # Find all URLs in the given text
    urls = re.findall(url_regex, text)
    return urls

# Example usage: Extract URLs from a sample text
sample_text = "Check out this website: https://www.example.com and this one: http://www.test.com"
print(extract_urls(sample_text))

Enter fullscreen mode Exit fullscreen mode

This script uses regular expressions, a powerful tool in text processing, to sift through any text and pull out the URLs. Its quick, efficient, and extremely useful for content creators and data enthusiasts alike.

From CSV to JSON: Streamline Your Data

In our data-driven world, converting data formats is a common task. One such task is turning a CSV file into a JSON file. This Python snippet takes a CSV file and converts it to a JSON file, making data manipulation and storage more convenient:


import csv
import json

def csv_to_json(csv_file_path, json_file_path):
    # Container for the data
    data = []
    # Open and read the CSV file
    with open(csv_file_path, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        # Add each row of the CSV file to the data container
        for row in csv_reader:
            data.append(row)

    # Open and write to the JSON file
    with open(json_file_path, mode='w') as json_file:
        json_file.write(json.dumps(data, indent=4))

# Example usage: Convert 'data.csv' to 'data.json'
csv_to_json('data.csv', 'data.json')

Enter fullscreen mode Exit fullscreen mode

Whether youre a budding data analyst or just someone who loves organizing data, this snippet will surely make your tasks a bit lighter.

In Conclusion

These Python snippets are just the tip of the iceberg when it comes to simplifying your digital life. Theyve been a game-changer for me, and I hope you find them just as useful. Python really is like having a magic wand for your files and data!

Feel free to play around with these scripts, tweak them to your needs, and watch as your tedious tasks become a breeze. Happy coding!

Ive tried to keep the tone light and relatable, focusing on the practical aspects of these snippets. Would you like to proceed with creating an SEO overview for this article, including keyword suggestions and other optimizations?

Top comments (0)