Library of small Python custom functions
- tinyytopic.com
- 0
- on Feb 16, 2023
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:
- 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. - The
ifstatement checks if thef_pathvariable contains a valid value (i.e., it is notNone). Iff_pathis empty orNone, the function immediately returns with no value. - If the
f_pathvariable contains a valid value, the function returns the value off_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:
- 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. - The
ifstatement checks if thef_pathvariable contains a valid value (i.e., it is notNone). Iff_pathis empty orNone, the function immediately returns with no value. - If the
f_pathvariable contains a valid value, the function returns the value off_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:
txt: a string in which the function will search for a substring located between two other substrings.first_char: the substring that marks the beginning of the substring we want to extract.last_char: the substring that marks the end of the substring we want to extract.start_location: the index intxtwhere the search will begin. By default, it is set to 0.
The function returns a tuple containing two values:
output_char: the substring located betweenfirst_charandlast_char. If no such substring is found, the value is set to'Not found!'.EndLoc: the index intxtwhere the search ended.
Here’s a step-by-step explanation of how the function works:
- The variable
output_charis initialized to the string'Not found!', and the variableEndLocis initialized to 0. - The variable
InitLocis set to the index of the first occurrence offirst_charintxt, starting the search from the index given bystart_location. Thefindmethod returns -1 if the substring is not found, so we addlen(first_char)toInitLocto get the index where the substring we want to extract begins. IfInitLocis less thanlen(first_char), it means thatfirst_charwas not found, so we return the tuple(output_char, EndLoc). - The variable
EndLocis set to the index of the first occurrence oflast_charintxt, starting the search from the index given byInitLoc. IfEndLocis less than 1, it means thatlast_charwas not found, so we return the tuple(output_char, EndLoc). - The variable
output_charis set to the substring oftxtthat starts atInitLocand ends atEndLoc. We then use thejoinandsplitmethods to remove any consecutive whitespace characters in the substring. - 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