Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Sunday, May 18, 2025

List All Files From All Subdirectories - Python


import os

target = 'c:\\Python38-64'

for x in os.walk(target):
    print(x)

The os.walk() function generates the file names in a directory tree by walking the tree either top-down or bottom-up, using a generator. It returns a 3-tuple (dirpath, dirnames, filenames) for each directory in the tree, where dirpath is a string of the path to the directory, dirnames is a list of the names of the subdirectories in dirpath, and filenames is a list of the names of the non-directory files in dirpath.

os.walk(target) is used to generate and print the 3-tuples for each directory in the tree starting at target. The output will show the directory tree structure, with each directory and its subdirectories listed under the preceding directory, and the non-directory files listed under their respective directory. 

import os

target = 'c:\\Python38-64'

for root, dirname, files in os.walk(target):
    for x in files:
        print(x)

This code uses the os module to traverse a directory tree rooted at c:\\Python38-64. The os.walk() function returns a generator object that yields three-tuples for each directory in the tree. Each three-tuple consists of a directory path (root), a list of subdirectory names (dirname), and a list of file names (files) in the directory root.

The for loop iterates over each three-tuple yielded by the os.walk() generator. For each three-tuple, the loop iterates over each file name in the files list and prints it to the console. This effectively prints the name of every file in the c:\\Python38-64 directory tree. 


import os

target = 'c:\\Python38-64'

for root, dirname, files in os.walk(target):
    for x in files:
        print(root + '\\' + x)

This code uses the os.walk() function to iterate through all the directories and files in the specified target directory and its subdirectories.

The os.walk() function returns a generator that produces a 3-tuple on each iteration: the root directory of the current iteration, a list of subdirectory names in the current iteration, and a list of file names in the current iteration.

In this code, we are unpacking the 3-tuple into root, dirname, and files. root is the current root directory being iterated over, dirname is a list of subdirectory names in the current root directory, and files is a list of file names in the current root directory.

The for loop then iterates over each file name in files and prints out the full file path by concatenating root and the file name with the backslash (\\) character used as a directory separator on Windows. The resulting output is a list of all the files in the target directory and its subdirectories with their full paths. 

import os

target = 'c:\\Python38-64'

for root, dirname, files in os.walk(target):
    for x in files:
        if x.endswith('.py'):
            print(root + '\\' + x)

This code uses the os module to traverse the file system starting at the given target directory (c:\Python38-64) and walk through all directories and subdirectories within it. For each file found within this directory and its subdirectories, the code checks whether the filename ends with the extension .py. If the file has this extension, it prints out the full path to the file (using root and x). This code can be useful if you need to find all Python source code files within a particular directory hierarchy.

Friday, May 2, 2025

Remote Administration Tool - Python - File Upload - [ Part 8 ]

Remote Administration Tool - Python - File Download - [ Part 7 ]

Remote Administration Tool - Python - Remove Directory - [ Part 6 ]

Remote Administration Tool - Python - TXT Reports and Directory Creation - [ Part 5 ]

Remote Administration Tool - Python - Change Directory - [ Part 4 ]

Remote Administration Tool - Python - Restrictions - [ Part 3 ]

Remote Administration Tool - Python - Subprocess Module - [ Part 2 ]

Remote Administration Tool - Python - Server and Client - [ Part 1 ]

Python Remote Administration

  1. Remote Administration Tool - Python - Server and Client - [ Part 1 ]
  2. Remote Administration Tool - Python - Subprocess Module - [ Part 2 ]
  3. Remote Administration Tool - Python - Restrictions - [ Part 3 ]
  4. Remote Administration Tool - Python - Change Directory - [ Part 4 ]
  5. Remote Administration Tool - Python - TXT Reports and Directory Creation - [ Part 5 ]
  6. Remote Administration Tool - Python - Remove Directory - [ Part 6 ]
  7. Remote Administration Tool - Python - File Download - [ Part 7 ]
  8. Remote Administration Tool - Python - File Upload - [ Part 8 ]

Thursday, May 1, 2025

Python & SQLite Tutorials

  1. SQLite & Python - Create Database
  2. SQLite & Python - Create Table
  3. SQLite & Python - Insert Into Table
  4. SQLite & Python - Insert Values to a Table from User Input
  5. SQLite & Python - Insert Muiltiple Values from List
  6. SQLite & Python - Read Rows from SQLite Table
  7. SQLite & Python - Update Statement
  8. SQLite & Python - Create Views
  9. SQLite & Python - Add New Column and Default Values
  10. SQLite & Python - Delete (DROP) Tables, Views, Rows

Python Examples

Socket Programming - Python

Security & Networks - Python

File & System Operations - Python

MySQL Python Examples - Python

ZIP Examples - Python

Audio Programming - Python

Python Tutorial

  1. Python Intro - Why to Learn Python
  2. Python Installation, First Script
  3. Python Prompt, CMD, Terminal
  4. Python Syntax, Indentation
  5. Python Comments, DocStrings
  6. Python Variables, Contexts
  7. Python Concatenation, Types
  8. Python Numbers
  9. Python Casting, int, float, str
  10. Python Indexing, Space Striping
  11. Python Strings, len, lower, upper
  12. Python Replace, Split
  13. Python Keyboard Input
  14. Python Lists
  15. Python Length, Indexes
  16. Python Change, Insert, Append
  17. Python Delete, Remove, Pop
  18. Python Search, Clear
  19. Python Tuples
  20. Python Tuples, Operations
  21. Python Sets
  22. Python Sets, Add, Update
  23. Python Sets, Remove Discard
  24. Python Dictionaries
  25. Python Dictionary Operations
  26. Python If, elif, else
  27. Python While Loops
  28. Python Break, Continue
  29. Python For Loops
  30. Python Dictionary Iteration
  31. Python Functions
  32. Python Function Arguments
  33. Python Keyboard Arguments
  34. Python Return Multiple Values
  35. Python Iteration, Iter, Next
  36. Python Modules
  37. Python Standard Library Examples
  38. Python Files, Reading
  39. Python Files, Write, Append
  40. Python Delete Files, Folders
  41. Python Try, Except, Finally

Wednesday, April 30, 2025

How to Generate CTCSS Tones - Python

Change frequency and duration to suit your needs. 

import math
import numpy as np
import pyaudio

# Define the frequency and duration of the tone
frequency = 88.5  # Hz
duration = 360  # seconds

# Generate the audio samples
samples_per_second = 44100
num_samples = samples_per_second * duration
x = np.arange(num_samples)
samples = 0.5 * np.sin(2 * np.pi * frequency * x / samples_per_second)

# Initialize PyAudio
p = pyaudio.PyAudio()

# Open a stream and play the audio
stream = p.open(format=pyaudio.paFloat32,
                channels=1,
                rate=samples_per_second,
                output=True)
stream.write(samples.astype(np.float32).tostring())

# Close the stream and PyAudio
stream.stop_stream()
stream.close()
p.terminate()

First, the necessary modules are imported:

  • math for mathematical functions
  • numpy as np for scientific computing with Python
  • pyaudio for audio input/output

The frequency and duration of the audio tone to be generated are then defined with the following lines: 

frequency = 88.5  # Hz
duration = 360  # seconds

The number of samples to generate is calculated based on the desired frequency and duration, along with the samples per second value: 

samples_per_second = 44100
num_samples = samples_per_second * duration

A numpy array x is generated to represent the time values for the audio samples to be generated: 

x = np.arange(num_samples)

The audio samples themselves are then generated as a sine wave with an amplitude of 0.5: 

samples = 0.5 * np.sin(2 * np.pi * frequency * x / samples_per_second)

PyAudio is then initialized: 

p = pyaudio.PyAudio()

An audio stream is opened with the desired format (32-bit floating point), number of channels (1), and sample rate (samples per second). The output parameter is set to True to indicate that audio should be played through the stream: 

stream = p.open(format=pyaudio.paFloat32,
                channels=1,
                rate=samples_per_second,
                output=True)

The audio samples are then written to the stream, converted to a string of 32-bit floating point values: 

stream.write(samples.astype(np.float32).tostring())

Finally, the stream is closed and PyAudio is terminated: 

stream.stop_stream()
stream.close()
p.terminate()

Monday, April 28, 2025

IRC Bot in Python - Passive IRC Client

This Python script will connect to IRC server and lurk in background. 

 

We are doing network related programming, so first thing is to import socket module. 

We need it to prepare IPv4 connection (socket.AF_INET) with TCP (socket.SOCK_STREAM).

HOST will hold IRC server domain, PORT 6667 will almost always work, and set NICK to something you desire. 

After that we will use s.connect((HOST, PORT)) to prepare for data sending.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = 'irc.libera.chat' #irc server
PORT = 6667 #port
NICK = 'YourNick'

s.connect((HOST, PORT))

First we will send NICK data finishing with '\r\n'. Sure, we will encode commands with .encode() method.

Same stuff with USER command. IRC is weird one, yes you need 3 "usernames" and one "real name". 

Read more about why at SO excellent link.

After that, we will JOIN #programming channel in this case. Don't forget encoding.

nick_data = ('NICK ' + NICK + '\r\n')
s.send(nick_data.encode())

usernam_data= ('USER YourNick1 YourNick2 YourNick3 :YourNick4 \r\n')
s.send(usernam_data.encode())

s.send('JOIN #programming \r\n'.encode()) #channel

With "while True" we will constantly check for incoming traffic to catch IRC server PING request. Because it's a must to respond with PONG.

Decode incoming stuff as UTF-8, and print results (chat). If PING is at the start of the stream, send same string with PONG. Encode it.

while True:
    result = s.recv(1024).decode('utf-8')
    print(result)

Just use 4 characters after PING (result[0:4) to grab what we need to return back.

 if result[0:4] == "PING":
        s.send(("PONG" + result[4:] + "\r\n").encode())

If length of the received message from IRC server is 0, than probably theres problem with connection so we will just break from script.

 if len(result) == 0:
        break        

Full script:  

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = 'irc.libera.chat' #irc server
PORT = 6667 #port
NICK = 'YourNick'

s.connect((HOST, PORT))

nick_data = ('NICK ' + NICK + '\r\n')
s.send(nick_data.encode())

usernam_data= ('USER YourNick1 YourNick2 YourNick3 :YourNick4 \r\n')
s.send(usernam_data.encode())

s.send('JOIN #programming \r\n'.encode()) #channel
while True:
    result = s.recv(1024).decode('utf-8')
    print(result)

    if result[0:4] == "PING":
        s.send(("PONG" + result[4:] + "\r\n").encode())

    if len(result) == 0:
        break        
        

Learn More:

Free Python Programming Course
Python Examples
Python How To
Python Modules 

YouTube WebDevPro Tutorials

Ping Multiple IP Addresses - Scan Network with Ping - Python

To use ping, we will import os module. To have a little bit of pause between pings, time module is needed.

Variable ip will hold left part of IP address, as a base for full IP. 

import os, time

ip = "192.168.0."

To go through all range of IPs for loop is needed (1, 255)Pause is set to 5 seconds between pings.

Results of pinging for every individual ip address will end up in - result. We will send just one packet, no need for 4 of them. It will be too slow.

Secondary for loop is needed to check for "TTL" string in system return. You can see that with normal pinging in terminal or command prompt if you are on Windows.

for x in range(1, 255):
    time.sleep(5)
    result = os.popen("ping -n 1 " + ip + str(x))

    for linija in result.readlines():
        if "TTL" in linija:
            print("DETECTED: ", linija)

If we are unable to ping IP, that networking device is probably off, so we will just print that.

else:
        print("OFF !", ip + str(x))

 Full Script:

import os, time

ip = "192.168.0."

for x in range(1, 255):
    time.sleep(5)
    result = os.popen("ping -n 1 " + ip + str(x))

    for linija in result.readlines():
        if "TTL" in linija:
            print("DETECTED: ", linija)
    else:
        print("OFF !", ip + str(x))
    

Learn More:

Free Python Programming Course
Python Examples
Python How To
Python Modules 

YouTube WebDevPro Tutorials

Number Stations as Screensaver - Random Number Generator - Python

This Python script will emulate number station stream. You can use it as screensaver or just for experiments. 

Random module is for, well, randomness, and time module is for pause between generations.

import random, time

While True is needed so this random number generator will work constantly.


Variables rn from 1 to 4 will hold random number from 1000 to 9999. 

    rn_1 = random.randint(1000, 9999)
    rn_2 = random.randint(1000, 9999)
    rn_3 = random.randint(1000, 9999)
    rn_4 = random.randint(1000, 9999)

After that, you can just print variables, or, of you need more numbers just multiply existing variables with some constant as 0.8 or something.

    print(rn_1, '\t', int(rn_1*0.8), '\t',
          int(rn_2), '\t',int(rn_2*0.8), '\t',
          int(rn_3), '\t',int(rn_3*0.8), '\t',
          int(rn_4), '\t',int(rn_4*0.8), '\t')
    time.sleep(1)

You can have as menu random numbers as you like :)

Full Script: 

import random, time

while True:
    rn_1 = random.randint(1000, 9999)
    rn_2 = random.randint(1000, 9999)
    rn_3 = random.randint(1000, 9999)
    rn_4 = random.randint(1000, 9999)
    
    print(rn_1, '\t', int(rn_1*0.8), '\t',
          int(rn_2), '\t',int(rn_2*0.8), '\t',
          int(rn_3), '\t',int(rn_3*0.8), '\t',
          int(rn_4), '\t',int(rn_4*0.8), '\t')
    time.sleep(1)

Learn More:

Free Python Programming Course
Python Examples
Python How To
Python Modules 

YouTube WebDevPro Tutorials

Detect Key Presses with Python

 With this simple Python script we will detect keypresses.

If you don't have pynput module, just type this in cmd: "pip install pynput".

We need two custom functions, press_on() will be activated when you press buttons, and press_off() will be activated on release.

If we press Escape, script will terminate.

This is just simple printing on screen, but you can upgrade your functions to do many other things.

from pynput.keyboard import *

def press_on(key):
    print('Press ON {}'.format(key))

def press_off(key):
    print('Press OFF: {}'.format(key))
    if key == Key.esc:
        return False

with Listener(on_press = press_on, on_release = press_off) as listener:
    listener.join()

Learn More:

Free Python Programming Course
Python Examples
Python How To
Python Modules 

YouTube WebDevPro Tutorials

Get Mouse Coordinates (x, y) with Python

This Python script is base for some bigger solutions you need. It will grab mouse coordinates, so you can work on them more.

Make sure that you have pynput module installed, if no, just type "pip install pynput" in cmd.

Simple function get_coords() will just print coordinates on screen.

from pynput import *

def get_coords(x, y):
    print("Now at: {}".format((x, y)))

with mouse.Listener(on_move = get_coords) as listen:
    listen.join()

Learn More:

Free Python Programming Course
Python Examples
Python How To
Python Modules 

YouTube WebDevPro Tutorials

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 .  ...