Monday, April 21, 2025

Create Empty Folder using Python

import os

os.chdir('c:\\')

os.system('mkdir BACKUP-1')

This code uses the os module to create a new directory called BACKUP-1 in the root directory of the C: drive (c:\\).

import os

os.chdir('c:\\')

The first line of code imports the os module.

The os.chdir() function is used to change the current working directory to the root directory of the C: drive (c:\\). This is done to ensure that the new directory is created in the correct location.

os.system('mkdir BACKUP-1')

The os.system() function is then called with the argument 'mkdir BACKUP-1'. This command is executed in the command prompt to create a new directory called BACKUP-1 in the current working directory, which is the root directory of the C: drive in this case. The os.system() function allows us to execute a shell command from within our Python script.

This code is useful for automating the creation of new directories for backups or for organizing files on your computer.

Copy Folder with Files to Another Folder - Python

import os, shutil

os.chdir('c:\\Python38-64\\')

shutil.copytree('SOURCE', 'DESTINATION')

This code uses the os and shutil modules to copy an entire directory called SOURCE from the current working directory (c:\\Python38-64\\) to a new directory called DESTINATION.

import os, shutil

os.chdir('c:\\Python38-64\\')

The first line of code imports the os and shutil modules.

The os.chdir() function is used to change the current working directory to c:\\Python38-64\\. This is done to ensure that the source directory, SOURCE, is located in the correct directory before it is copied.

shutil.copytree('SOURCE', 'DESTINATION')

The shutil.copytree() function is then called with two arguments: the source directory (SOURCE) and the destination directory (DESTINATION). The shutil module provides a way to copy files and directories in a platform-independent manner.

This code is useful for creating backups of entire directories in a way that is quick and easy to automate. However, it should be noted that overwriting an existing directory with the same name as the destination directory may result in the loss of the original directory and its contents.

Copy File to Same Folder - Python

import os, shutil

os.chdir('c:\\Python38-64\\')

shutil.copy('copy-me.txt', 'backup-n-1.txt')

This code uses the os and shutil modules to copy a file called copy-me.txt from the current working directory (c:\\Python38-64\\) to a new file called backup-n-1.txt in the same directory.

import os, shutil

os.chdir('c:\\Python38-64\\')

The first line of code imports the os and shutil modules.

The os.chdir() function is used to change the current working directory to c:\\Python38-64\\. This is done to ensure that the source file, copy-me.txt, is located in the correct directory before it is copied.

shutil.copy('copy-me.txt', 'backup-n-1.txt')

The shutil.copy() function is then called with two arguments: the source file (copy-me.txt) and the destination file (backup-n-1.txt). The shutil module provides a way to copy files and directories in a platform-independent manner.

This code is useful for creating backups of important files in a way that is quick and easy to automate. However, it should be noted that overwriting an existing file with the same name as the destination file may result in the loss of the original file.

Backup One File with Python - Simple Backup Script

import os, shutil

os.chdir('c:\\Python38-64\\')

shutil.copy('copy-me.txt', 'c:\\EXTERNAL-ARCHIVE')

This code uses the os and shutil modules to copy a file called copy-me.txt from the current working directory (c:\\Python38-64\\) to a directory called EXTERNAL-ARCHIVE located at the root of the C: drive.

import os, shutil

os.chdir('c:\\Python38-64\\')

The first line of code imports the os and shutil modules.

The os.chdir() function is used to change the current working directory to c:\\Python38-64\\. This is done to ensure that the source file, copy-me.txt, is located in the correct directory before it is copied.

shutil.copy('copy-me.txt', 'c:\\EXTERNAL-ARCHIVE')

The shutil.copy() function is then called with two arguments: the source file (copy-me.txt) and the destination directory (c:\\EXTERNAL-ARCHIVE). The shutil module provides a way to copy files and directories in a platform-independent manner.

This code is useful for automating file backup or archiving tasks, where files need to be regularly copied or moved from one location to another.

Redirect Command Prompt Operation to .TXT File

import os

list_targets = ['localhost', 'yahoo.com', 'google.com']

file = open('bulk-report.txt', 'w')

for x in list_targets:
    response = os.popen('ping ' + x)

    for y in response.readlines():
        file.write(y)

file.close()
            

The code starts by importing the os module, which provides a way to interact with the operating system and run system commands. Then, a list called list_targets is created, which contains three target addresses: localhost, yahoo.com, and google.com.

import os list_targets = ['localhost', 'yahoo.com', 'google.com']

Next, the code creates a new file called bulk-report.txt in write mode using the open() function and assigns the file object to a variable called file.

file = open('bulk-report.txt', 'w')

A for loop is used to iterate over each target address in the list_targets. For each target address, the os.popen() function is called with the ping command and the target address as an argument. The os.popen() function runs the command and returns the output of the command as a file-like object.

for x in list_targets:
    response = os.popen('ping ' + x)

Inside the for loop, another for loop is used to iterate over each line of output from the ping command using the readlines() method. For each line, the code writes the line to the file object using the write() method.

for y in response.readlines():
        file.write(y)

Finally, after all the target addresses have been processed, the file object is closed using the close() method.

file.close()

This code can be used to automate pinging multiple hosts and save their output to a file, which can be useful for monitoring or troubleshooting network issues. However, it should be noted that the ping command may not work on all systems, and some firewalls or routers may block ICMP traffic.

Exporting all "prints" to external .TXT file

import socket

file = open('bulk-domains.txt', 'r')

domain_list = []

for x in file.readlines():
    domain_list.append(x.rstrip())

report = open('domains.txt', 'w')

for y in domain_list:
    report.write("-" * 45 + '\n')
    report.write(y + '\t->\t' + socket.gethostbyname(y) + '\n')

report.close()

This code opens a file called 'bulk-domains.txt' in read-only mode using the open() function and assigns the file object to a variable called file. Then, an empty list called domain_list is created.

The for loop iterates through each line in the file object using the readlines() method. rstrip() method is used to remove any newline characters or whitespace from the end of each line, and the cleaned-up line is appended to the domain_list using the append() method.

import socket

file = open('bulk-domains.txt', 'r')
domain_list = []

for x in file.readlines():
    domain_list.append(x.rstrip())

After the domain_list has been populated with domain names, the code creates a new file called domains.txt in write mode using the open() function and assigns the file object to a variable called report.

The next for loop iterates through each domain name in the domain_list, and for each domain name, it writes a separator line consisting of 45 dashes using string multiplication. It then writes the domain name followed by the IP address of that domain name obtained by using the socket.gethostbyname() method, which performs a DNS lookup to resolve the domain name to its IP address.

report = open('domains.txt', 'w')

for y in domain_list:
    report.write("-" * 45 + '\n')
    report.write(y + '\t->\t' + socket.gethostbyname(y) + '\n')

Finally, the report file is closed using the close() method.

report.close()

This code is useful for performing bulk DNS lookups to obtain the IP addresses of a large number of domain names, and can be modified to suit various use cases.

Creating Simple Command Line App - Python

import socket, os

os.system('cls')

print("#" * 79)
print("Custom Domain to IP Script v: 0.1")
print("#" * 79)
print('\n\n')

file = open('bulk-domains.txt', 'r')

domain_list = []

for x in file.readlines():
    domain_list.append(x.rstrip())

for y in domain_list:
    print("-" * 79)
    print(y + '\t->\t' + socket.gethostbyname(y))

Here is a line-by-line explanation of the Python script:

import socket, os

This line imports the socket and os modules, which will be used to perform DNS resolution and clear the console screen.

os.system('cls')

This line uses the os.system() function to run the "cls" command, which clears the console screen. This ensures that the output of the script is displayed cleanly.

print("#" * 79)
print("Custom Domain to IP Script v: 0.1")
print("#" * 79)

These lines print a banner at the top of the console window. The banner is made up of a row of "#" characters and the name and version number of the script.

file = open('bulk-domains.txt', 'r')
domain_list = []
for x in file.readlines():
    domain_list.append(x.rstrip())

These lines open a file called "bulk-domains.txt" in read mode and read its contents line by line. Each line is added to a list called domain_list, with any trailing newline characters removed using the rstrip() method.

for y in domain_list:
    print("-" * 79)
    print(y + '\t->\t' + socket.gethostbyname(y))

These lines loop through each domain in domain_list and use the socket.gethostbyname() function to perform a DNS lookup and resolve the domain to an IP address. The domain name and its corresponding IP address are printed to the console, separated by a tab character and an arrow symbol. A row of "-" characters is printed before each domain name to visually separate them.

That's it! This script reads a list of domain names from a file, performs a DNS lookup for each domain, and prints the results to the console. It's a simple but useful tool for anyone who needs to perform bulk DNS lookups.

Taking Continous Input from User - Python

import os

while True:
    app = input('Please, enter App to run: ')

    if app == 'quit':
        print('I am done here')
        break
    else:
        os.system(app)

This Python code imports the "os" module using the "import" statement.

The code then enters an infinite "while" loop using the "while True" statement. The purpose of this loop is to repeatedly ask the user to enter the name of an application to run.

Inside the loop, the code uses the "input()" function to prompt the user to enter the name of an application to run. The user's input is stored in the variable "app".

The code then checks whether the value of "app" is equal to the string "quit" using an "if" statement. If the value of "app" is "quit", the message "I am done here" is printed to the console screen using the "print()" function, and the "break" statement is used to exit the loop.

If the value of "app" is not "quit", the "else" block is executed. In this case, the "os.system()" function is used to execute the application named "app". The "os.system()" function is a built-in function in the "os" module that allows the user to execute operating system commands.

So, when the program is executed, the code will enter an infinite loop and repeatedly ask the user to enter the name of an application to run. If the user enters the string "quit", the program will exit the loop and print the message "I am done here" to the console screen. If the user enters the name of an application, the "os.system()" function will be used to execute that application.

Try, Except and Finally - Python Exception Handling

import os

try:
    os.remove('test-file.txt')
    print('File Deleted')
except:
    print('Script fails - there\'s no file there')
finally:
    os.system('ping google.com')

This Python code imports the "os" module using the "import" statement.

The code then enters a "try-except-finally" block. The "try" block attempts to delete a file named "test-file.txt" using the "os.remove()" function. If the file does not exist or the user does not have permission to delete the file, the "os.remove()" function will raise an error. If the file is successfully deleted, the message "File Deleted" is printed to the console screen using the "print()" function.

If the "try" block raises an exception, the "except" block is executed. In this case, the "except" block will print the message "Script fails - there's no file there" to the console screen using the "print()" function.

The "finally" block is always executed, regardless of whether the "try" or "except" blocks were executed. In this case, the "finally" block calls the "os.system()" function to execute the "ping google.com" command. This command pings the Google website to test the network connectivity.

So, when the program is executed, the code will first attempt to delete the "test-file.txt" file using the "os.remove()" function. If the file is successfully deleted, the message "File Deleted" is printed to the console screen. If the file does not exist or the user does not have permission to delete the file, the message "Script fails - there's no file there" is printed to the console screen.

Finally, regardless of whether the file was deleted or not, the "os.system()" function is called to execute the "ping google.com" command to test the network connectivity.

Pause Execution of Program in Python - time.sleep() Example

import time

names = ["Michael", "Samantha", "John"]

for x in names:
    print('Printing now: ' + x)
    time.sleep(2)

This Python code imports the "time" module using the "import" statement.

The code initializes a list variable named "names" with three string values: "Michael", "Samantha", and "John".

The code then enters a "for" loop that iterates over each element (a string value) of the "names" list. In each iteration of the loop, the code prints a message to the console screen using the "print()" function. The message being printed is "Printing now: " concatenated with the string value of the current element of the "names" list.

After printing the message, the "time.sleep()" function is used to pause the program execution for 2 seconds, which creates a delay before the next iteration of the loop.

The combination of these statements creates a program that prints a message with the name of each person in the "names" list to the console screen with a delay of 2 seconds between each name.

So, when the program is run, the console screen will display the message "Printing now: Michael", followed by a 2-second pause, then the message "Printing now: Samantha", followed by another 2-second pause, and finally the message "Printing now: John".

Delete File - os.remove() Example

import os

files = ['new-1.txt', 'new-2.txt', 'new-3.txt']

for x in files:
    os.remove(x)

This Python code imports the "os" module using the "import" statement.

Then, the code initializes a list variable named "files" with three string values: 'new-1.txt', 'new-2.txt', and 'new-3.txt'.

The code then enters a "for" loop that iterates over each element (a string value) of the "files" list. In each iteration of the loop, the code calls the "os.remove()" function to delete the file with the corresponding file name from the current working directory. The name of the file to be deleted is passed as an argument to the "os.remove()" function.

So, when the program is executed, the files with the names 'new-1.txt', 'new-2.txt', and 'new-3.txt' will be deleted from the current working directory. If the files do not exist in the directory, the "os.remove()" function will raise a "FileNotFoundError".

How to Clear Screen in Terminal - Python

import os, time

for x in range(5):
    os.system('cls')
    print('Do you feel lucky, punk ? ')
    time.sleep(2)

This Python code imports two modules, "os" and "time", using the "import" statement.

The code then enters a "for" loop that iterates over a range of values from 0 to 4 (inclusive). In each iteration of the loop, the code executes two statements:

  1. The "os.system()" function is used to execute a command on the operating system shell. In this case, the command being executed is 'cls', which is used to clear the console screen on Windows systems.

  2. The "print()" function is used to print a message to the console screen. In this case, the message being printed is "Do you feel lucky, punk ? ".

After printing the message, the "time.sleep()" function is used to pause the program execution for 2 seconds, which creates a delay before the next iteration of the loop.

The combination of these statements creates a program that clears the console screen and displays a message repeatedly for a total of 5 times, with a delay of 2 seconds between each message.

So, when the program is run, the console screen will be cleared and the message "Do you feel lucky, punk ?" will be printed to the screen repeatedly for a total of 5 times, with a delay of 2 seconds between each message.

Splitting UNIX Path - Python

path = '/var/log/messages'

res = path.split('/')

print(res)

This Python code initializes a string variable named "path" with the value "/var/log/messages", and then splits the string based on the '/' character using the "split()" method.

The "split()" method divides the original string into substrings at each occurrence of the specified separator character ('/'), and returns a list of the resulting substrings.

The resulting list is assigned to a new variable named "res".

Finally, the code prints the value of the "res" variable using the "print()" function.

So, the output of the given code will be a list of strings, where each element in the list corresponds to a substring between the separator character '/' in the original string. In this case, the output will be:

['', 'var', 'log', 'messages']

The first element of the list is an empty string, which corresponds to the substring before the first occurrence of the separator character. The other elements of the list correspond to the substrings between the separator characters. 

Path Elements

path = '/var/log/messages'

res = path.split('/')

print(res[0])
print(res[1])
print(res[2])
print(res[3])

 Output of the given code will be:

 
var
log
messages

This is because the "res" list contains four elements, corresponding to the substrings between the separator character '/' in the original string.

The first element of the list (at index 0) is an empty string, which corresponds to the substring before the first occurrence of the separator character. The other elements of the list (at indices 1 to 3) correspond to the substrings between the separator characters.

By printing each element of the "res" list using its index, the code prints each substring in the original string as a separate line of output.

Export to txt file

 

path = '/var/log/messages'

res = path.split('/')

file = open('export.txt', 'w')

for x in res:
    file.write(x + '\n')

file.close()

The code then creates a new file named "export.txt" using the "open()" function in write mode ('w').

The code then enters a for loop that iterates over each element of the "res" list. In each iteration, the code writes the current element (a substring of the original "path" string) to the file using the "write()" method of the file object, and then adds a newline character ('\n') to the end of the written string to separate each substring on a new line.

Finally, the code closes the file using the "close()" method.

So, the output of the given code will be a new file named "export.txt" containing the following text:

 
var
log
messages

This is because the for loop iterates over each substring in the "res" list, and writes each substring to a new line in the "export.txt" file, separated by a newline character. Each substring corresponds to a directory name or filename in the original "path" string.

Directory Listing with os.listdir in Python

import os

path = 'c:\\Python38-64'

print(os.listdir(path))

The given code is importing the "os" module, which is a built-in module in Python that provides a way of interacting with the operating system.

The variable 'path' is set to the string 'c:\Python38-64', which represents the directory path in the Windows operating system where Python version 3.8-64 is installed.

The "os.listdir(path)" method is used to list all the files and directories present in the directory specified by 'path'. This method returns a list of filenames and directory names as strings.

Finally, the list of files and directories present in the specified path is printed to the console using the print() function.

So, the output of the given code will be a list of files and directories present in the 'c:\Python38-64' directory on the Windows operating system.


import os

path = 'c:\\Python38-64'

res = os.listdir(path)

for x in res:
    print(x)

The "for" loop is used to iterate over each item in the "res" list. Each item in the list represents a file or a directory in the specified path.

Within the loop, the "print()" function is used to print each file or directory name to the console.

import os

path = 'c:\\Python38-64'

res = os.listdir(path)

for x in range(5):
    print(res[x])

The "for" loop is used to iterate over the first five items in the "res" list, which represent the first five files or directories in the specified path.

Within the loop, the "print()" function is used to print each file or directory name to the console.

So, the output of the given code will be the first five files and directories present in the 'c:\Python38-64' directory on the Windows operating system, with each item printed on a new line. If there are fewer than five items in the directory, the loop will only iterate over the available items and the code will not raise any error.

Splitting Windows Path with Python

path = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"

res = path.split('\\')

print(res)

This Python code creates a string variable called "path" which contains the path to the Chrome application executable file on a Windows operating system. The backslashes used in the path are escape characters and need to be written as double backslashes to be properly recognized as part of the string.

The next line of code splits the path string into a list of strings based on the backslash separator using the split() method. The resulting list is assigned to a variable called "res".

Finally, the contents of the "res" list are printed to the console. This will output a list of strings, where each string is a portion of the original path string that was separated by the backslashes. The resulting list will contain the following strings: ['C:', 'Program Files (x86)', 'Google', 'Chrome', 'Application', 'chrome.exe']. 

Variant with a for loop

path = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"

res = path.split('\\')

for x in res:
    print(x)

Variant with export to external txt file


path = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"

res = path.split('\\')

file = open('external.txt', 'w')

for x in res:
    file.write(x + '\n')

file.close()

This Python script takes a file path, splits it using the backslash character ('') as a separator, and writes each element of the resulting list to a new line in a text file named 'external.txt'.

Here's a detailed explanation of each line:

  1. path = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" assigns a file path to the variable 'path'. This is a Windows path that points to the Google Chrome application executable.

  2. res = path.split('\\') splits the path string into a list of strings, using the backslash character as a separator. The resulting list is assigned to the variable 'res'.

  3. file = open('external.txt', 'w') creates a new text file named 'external.txt' in write mode and assigns it to the variable 'file'.

  4. for x in res: starts a loop that iterates through each element of the 'res' list, assigning each element to the variable 'x' in turn.

  5. file.write(x + '\n') writes the value of 'x' to the 'file' object, followed by a newline character ('\n') to create a new line in the text file.

  6. file.close() closes the 'file' object and saves the changes made to the text file.

In summary, this Python script extracts the components of a file path and writes them to a new text file, with each component on a new line. This can be useful for parsing file paths and extracting specific information from them.

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...