DEV Community

Cover image for Day 1 of Learning Scripting
SHIVAJEE
SHIVAJEE

Posted on

Day 1 of Learning Scripting

Hi, folks from today 26th Nov 2024, I have started learning scripting to become a Highly Skilled DevOps engineer.
Today I learned the basic workflow of scripting.

1. Basics of Scripting:- Scripting is used to automate the repetitive or routine works which is engineers often face in DevOps culture.

2. Applications of Scripting:- So, what are the applications of scripting?
It is commonly used in File Management such as renaming, organising, deleting, etc.
Other Application involves system monitoring, automation such as fetching APIs, backups etc.
3. Steps Involved to Automate a task:-
(i) The first step is to identify the problem and break it down into smaller pieces. eg.
"Renaming files" -> first list all the files -> Modify the names -> save with new names.
(ii) Choose a language, most commonly used in industries is Python or BASH, as they directly run without compilation.
(iii) Design the Workflow- eg. File renaming involves:

  1. Identify the directory
  2. Loop through files.
  3. Rename files using a pattern. (iv) Error Handling- Always ensure to handle issues like:-
  4. Missing files.
  5. Permission Denied.
  6. Invalid input. 4. Core Concepts involved in Scripting:- Variables: Store data for reusability. eg:- directory = "./files" Loops: Automate repetitive tasks. eg:- _for file in os.listdir(directory): print(file) _ Functions: Habit to modularise your script and keep it reusable. eg:- _def rename_file(old_name, new_name): os.rename(old_name, new_name) _ File Handling: Understanding of file handling is cruicial in Scripting. eg: _with open("abc.txt", "r") as f: data = f.read() _ 5. Common Tools and Libraries:- Python Libraries os:- Interacts with the operating system. shutil:- Advanced file operations. requests:- Fetches data from API.

Linux/BASH Commands
ls:- List Directory.
mv:- Rename or move files.
grep:- Searches within file.

Automate file renaming in Python:

To automate file renaming using Python, you can use the os and the glob modules.

Prerequisite:

  1. Python(3.x) should installed in the system.
  2. Familiarity with basic Python concepts.

Steps to Automate File Renaming:

Identify the Directory: The first step is to specify the directory where your files are located. You need to be able to access and modify these files programmatically.

List All Files: Use Python’s os or glob module to list the files in the target directory. You can filter files based on extension if needed.

Define the Renaming Pattern: Based on your needs, you can define a renaming pattern. This could involve adding prefixes, suffixes, or even modifying filenames based on a regex pattern.

Rename Files: Using the os.rename() function, rename each file based on your defined pattern. Ensure that you handle potential errors (e.g., file already exists, permission issues, etc.).

Example: Renaming Files Based on a Pattern

Below is a simple Python script to rename files in a directory, appending a prefix and suffix:

**_

import os

def rename_files_in_directory(directory, prefix, suffix, extension):
    # Change working directory to the target folder
    os.chdir(directory)

    # Get all files with the given extension
    for filename in os.listdir(directory):
        # Check if the file has the specified extension
        if filename.endswith(extension):
            # Define the new file name based on the prefix and suffix
            new_name = f"{prefix}_{filename[:-len(extension)]}_{suffix}{extension}"
            # Rename the file
            os.rename(filename, new_name)
            print(f"Renamed: {filename} -> {new_name}")
directory = r"C:\path\to\your\folder"  # Change this to your directory path
prefix = "new"  # Example: Adds "new" as prefix to filenames
suffix = "v1"  # Example: Adds "v1" as suffix to filenames
extension = ".txt"  # Modify this to match the file extension you're working with

rename_files_in_directory(directory, prefix, suffix, extension)
Enter fullscreen mode Exit fullscreen mode

`
_**
Explanation of the Script:
os.chdir(directory): Changes the working directory to the specified path so you can access the files.
os.listdir(directory): Lists all the files in the directory.
filename.endswith(extension): Filters files based on their extension (e.g., .txt).
os.rename(filename, new_name): Renames the file with the new name.

So, that's all for today, I will be posting regular updates about my Learning journey of Scripting.

Make sure to follow.

Top comments (0)