Library of small Python custom functions


How to open a folder directory?

A quick Python function to browse a folder:

def browse_open_folder_directory():
    f_path = filedialog.askdirectory()
    if not f_path: return
    return f_path

Write your main code as a sample below,

from tkinter import filedialog

print(browse_open_folder_directory())

A sample output of the code is,

C:\Downloads

How does the function work?

The Python function browse_open_folder_directory does not take any arguments, but it opens a dialog box using the filedialog module of the tkinter library. The dialog box allows the user to browse their system to select a folder or directory.

Here is a breakdown of how the function works:

  1. The filedialog.askdirectory() method is used to open a dialog box that allows the user to browse their system to select a folder or directory. This method returns the path of the selected folder or directory as a string.
  2. The if statement checks if the f_path variable contains a valid value (i.e., it is not None). If f_path is empty or None, the function immediately returns with no value.
  3. If the f_path variable contains a valid value, the function returns the value of f_path.

How to open a file directory?

A quick Python function to browse a file:

def browse_open_file_directory():
    f_path = filedialog.askopenfilename()
    if not f_path: return
    return f_path

Write your main code as a sample below,

from tkinter import filedialog

print(browse_open_file_directory())

A sample output of the code is,

C:\Downloads\scaled_image.jpg

How does the function work?

The Python function browse_open_file_directory does not take any arguments, but it opens a file dialog box using the filedialog module of the tkinter library. The dialog box allows the user to browse their system to select a file.

Here is a breakdown of how the function works:

  1. The filedialog.askopenfilename() method is used to open a dialog box that allows the user to browse their system to select a file. This method returns the path of the selected file as a string.
  2. The if statement checks if the f_path variable contains a valid value (i.e., it is not None). If f_path is empty or None, the function immediately returns with no value.
  3. If the f_path variable contains a valid value, the function returns the value of f_path.

How to find a string between two characters or strings?

A quick Python function to find a string between two strings:

def find_string_between_chars(txt, first_char, last_char, start_location=0):
    # Find a string between two characters in a text data
    
    output_char = 'Not found!'
    EndLoc = 0
    
    InitLoc = txt.find(first_char, start_location) + len(first_char)
    if InitLoc < len(first_char): return output_char, EndLoc
    
    EndLoc = txt.find(last_char, InitLoc)
    if EndLoc < 1: return output_char, EndLoc
    
    output_char = txt[InitLoc:EndLoc]
    output_char = ' '.join(output_char.split()) # replace continues white spaces with single space
    
    return output_char, EndLoc

Write your main code as a sample below,

txt = "The Python is a open source programming language!"
first_char = "a "
last_char = "prog"

output_char, end_loc = find_string_between_chars(txt, first_char, last_char)

print(output_char)

The output of the code is,

"open source"

How does the function work?

The Python function find_string_between_chars takes four parameters:

  1. txt: a string in which the function will search for a substring located between two other substrings.
  2. first_char: the substring that marks the beginning of the substring we want to extract.
  3. last_char: the substring that marks the end of the substring we want to extract.
  4. start_location: the index in txt where the search will begin. By default, it is set to 0.

The function returns a tuple containing two values:

  1. output_char: the substring located between first_char and last_char. If no such substring is found, the value is set to 'Not found!'.
  2. EndLoc: the index in txt where the search ended.

Here’s a step-by-step explanation of how the function works:

  1. The variable output_char is initialized to the string 'Not found!', and the variable EndLoc is initialized to 0.
  2. The variable InitLoc is set to the index of the first occurrence of first_char in txt, starting the search from the index given by start_location. The find method returns -1 if the substring is not found, so we add len(first_char) to InitLoc to get the index where the substring we want to extract begins. If InitLoc is less than len(first_char), it means that first_char was not found, so we return the tuple (output_char, EndLoc).
  3. The variable EndLoc is set to the index of the first occurrence of last_char in txt, starting the search from the index given by InitLoc. If EndLoc is less than 1, it means that last_char was not found, so we return the tuple (output_char, EndLoc).
  4. The variable output_char is set to the substring of txt that starts at InitLoc and ends at EndLoc. We then use the join and split methods to remove any consecutive whitespace characters in the substring.
  5. We return the tuple (output_char, EndLoc).

Create a directory if not exists

use the os module in Python to create a directory if it doesn’t exist already. Here’s an example function that takes a directory path as an argument and creates the directory if it doesn’t exist:

import os

def create_directory(path):
    if not os.path.exists(path):
        os.makedirs(path)


Write your main code as a sample below,

create_directory("/path/to/directory")

If the directory doesn’t exist, the function will create it and print a message saying that the directory was created. If the directory already exists, the function will print a message saying that the directory already exists.


Access the index of an element in ‘for’ loop:

In Python, you can access the index of an element in a sequence when iterating through it using a for loop by using the built-in function enumerate().


To start the index from 0 (Zero):

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):
    print(index, fruit)


To start the index from 1 (One):

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

Output:

1 apple
2 banana
3 cherry

Leave a Reply

Your email address will not be published. Required fields are marked *