Sunday, April 20, 2025

Python Try, Except, Finally

Simple if-else blocks will work just fine:


import os

print("Script to check removal of files")
print("-" * 50)

if os.path.exists("deleteme.txt"):
    print("File Detected")
    os.remove("deleteme.txt")
    print("File Removed")
else:
    print("No File There - Nothing To Delete")

Result: 


Script to check removal of files
--------------------------------------------------
File Detected
File Removed
>>> 

If you run script one more time - when there's no file there:


Script to check removal of files
--------------------------------------------------
No File There - Nothing To Delete
>>> 

But more elegant approach is to Try to do something, and if that fails, than we will activate code in Except section.

The best thing here is that code in Finally section will always run.

So, no metter what happens with code in Try/Except, we can always be sure that whatever we put in Finally will get some job done.

It's like backup operation that will always work.


import os

print("Script to check removal of files")
print("-" * 50)

try:
    os.remove("deleteme.txt")
    print("File Removed")
except:
    print("No file - Nothing to Delete")
finally:
    print("This will work - always")

Result: 


Script to check removal of files
--------------------------------------------------
File Removed
This will work - always
>>> 

After second run:


Script to check removal of files
--------------------------------------------------
No file - Nothing to Delete
This will work - always
>>> 

Congratulations - You just finished more than 40 Python Tutorials.

Python Delete Files, Folders

To delete files we will use os module, and remove() function:


import os

print("WARNING, files will be deleted")
print("-" * 50)

os.remove("external.txt")
os.remove("external_2.txt")

If we try to delete directory with content using rmdir(), operation will fail:


import os

print("Trying to delete Full Folder Will Fail")
print("-" * 50)

os.rmdir("FULL_FOLDER")

Result: 


Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 6, in <module>
    os.rmdir("FULL_FOLDER")
OSError: [WinError 145] The directory is not empty: 'FULL_FOLDER'
>>> 

That function can be used only on empty folders:


import os

print("With rmdir You Can delete only Empty Folder")
print("-" * 50)

os.rmdir("EMPTY_FOLDER")

Result: 


With rmdir You Can delete only Empty Folder
--------------------------------------------------
>>> 

What if you must delete folder and everything in it ? In that case, use "shutil" module and rmtree() function:


import shutil

print("With shutil.rmtree() You Can delete Full Folder")
print("-" * 50)

shutil.rmtree("FULL_FOLDER")

Result:


With shutil.rmtree() You Can delete Full Folder
--------------------------------------------------
>>> 

Well done.

It's time to learn about Try, Except and Finally blocks.

Python Files, Write, Append

To create a new file, or to overwrite existing one, use "w" as second argument:


f = open("external.txt", "w")

f.write("Line One")
f.write("Second One")
f.write("Third One")

f.close()

Result: 


Line OneSecond OneThird One

To evade concatenation, add "\n" at the end of every new line:


f = open("external.txt", "w")

f.write("Line One \n")
f.write("Second One \n")
f.write("Third One \n")

f.close()

Result: 


Line One 
Second One 
Third One 

If you need to add new content, without destruction of previous lines, use "a" as second argument:


f = open("external_2.txt", "a")

f.write("One More Time \n")
f.write("One More Time \n")
f.write("One More Time \n")

f.close()

Content of external_2.txt after we run code from above two times:


One More Time 
One More Time 
One More Time 
One More Time 
One More Time 
One More Time 

Sometimes we will need to delete files and folders. About that, in next tutorial.

Python Files, Reading

Our "source.txt" is simple, just three lines.

Use "f" as handle for operation. We will just read() all lines, so "r" is second argument:


f = open("source.txt", "r")

result = f.read()

print(result)

Result: 


first line
second line
third line

>>> 

If you need to read just specific number of bytes, you can pass that as argument:


f = open("source.txt", "r")

print(f.read(5))
print(f.read(5))
print(f.read(5))

Result:  


first
 line

seco
>>> 

For loops are also great here:


f = open("source.txt", "r")

for x in range(3):
    print(f.read(6))

Result:  


first 
line
s
econd 
>>> 

With function readline() we can read line by line:


f = open("source.txt", "r")

print(f.readline())
print(f.readline())
print(f.readline())

Result:  


first line

second line

third line

>>> 

If you need to extract all lines to list, use readlines() function:


f = open("source.txt", "r")

all_lines = f.readlines()

print(all_lines)
print(type(all_lines))

Result:  


['first line\n', 'second line\n', 'third line\n']
<class 'list'>
>>> 

Then we can target individual lines as elements:


f = open("source.txt", "r")

all_lines = f.readlines()

print(all_lines[0])
print(all_lines[1])
print(all_lines[2])

Result:  


first line

second line

third line

>>> 

Easy.

It't time to learn how to write and append to files.

Python Standard Library Examples

We will use "ftplib" module to establish connection to public remote FTP server.

Task will be to grab debian directory listing.

After we connect to host, login() function will be used to log in as "anon" user.

Then, we will relocate to "debian" directory with cwd() function.

Function retrlines() with argument "LIST" will be used to grab listing.

It's polite to close connection with close() function.


from ftplib import *

host = FTP("ftp.fi.debian.org")
host.login()
host.cwd("debian")
host.retrlines("LIST")

Result: 


-rw-r--r--    1 ftp      ftp          1185 Jul 18 11:48 README
-rw-r--r--    1 ftp      ftp          1290 Jun 26  2010 README.CD-manufacture
-rw-r--r--    1 ftp      ftp          2895 Jul 18 11:48 README.html
-rw-r--r--    1 ftp      ftp           291 Mar 04  2017 README.mirrors.html
-rw-r--r--    1 ftp      ftp            86 Mar 04  2017 README.mirrors.txt
drwxr-xr-x   19 ftp      ftp            41 Jul 18 11:50 dists
drwxr-xr-x    4 ftp      ftp            16 Jul 19 15:52 doc
-rw-r--r--    1 ftp      ftp        210880 Jul 19 16:22 extrafiles
drwxr-xr-x    3 ftp      ftp            58 Jul 19 16:17 indices
-rw-r--r--    1 ftp      ftp      12803150 Jul 19 16:17 ls-lR.gz
drwxr-xr-x    5 ftp      ftp             5 Dec 19  2000 pool
drwxr-xr-x    4 ftp      ftp             5 Nov 18  2008 project
drwxr-xr-x    3 ftp      ftp             5 Oct 10  2012 tools
drwxr-xr-x   20 ftp      ftp            20 Jul 07  2019 zzz-dists
>>> 

It's so easy to do this in Python.

Now it's time to learn how to read from file.

Python Modules

Modules are external files that hold additional source (functions) that we can use - if we need them.

Create file "external.py" - that will be our module with one function my_func(), for now:


def my_func():
    print("I am from external world...")

This is our main file where we are practicing: "playground.py". First we need to "import" external module (without extension ".py").

Then, just call our function from module, with dot in the middle:


import external

external.my_func()

Result: 


I am from external world...
>>> 

Functions in main file are also fine:


import external

external.my_func()

def localone():
    print("Local Stuff...")

localone()

Result: 


I am from external world...
Local Stuff...
>>> 

Create new module "anotherone.py" with this source:


print("AUTOMATIC print on module import")

Import "anotherone.py" into our main script:


import external, anotherone

external.my_func()

def localone():
    print("Local Stuff...")

localone()

Stuff from "anotherone.py" will be immediately executed when we run our mains script.

This can be security problem if you just like to grab things from Internet, without checking:


AUTOMATIC print on module import
I am from external world...
Local Stuff...
>>> 

We can use short names for modules:


import external as ex

ex.my_func()

Or we can grab everything from module in such a way that there's no need to type module name every time when we need specific function from that module:


from external import *

my_func()

Result: 


I am from external world...
>>> 

Next tutorial will be dedicated to practical example how to use modules from Standard Library.

Python Iteration, Iter, Next

With iter() function we will target specific list, and individual next() functions will be used to print elements of list:


colors = ["red", "blue", "yellow"]

target = iter(colors)

print(next(target))
print(next(target))
print(next(target))

Result: 


red
blue
yellow
>>> 

But for loops are more practical, especially if lists are big:


colors = ["red", "blue", "yellow"]

target = iter(colors)

for x in range(3):
    print(next(target))

Result: 


red
blue
yellow
>>> 

Can we use iteration on dictionaries ? Sure:


diction = {"name" : "Anastasia", "SSN" : 246546}

target = iter(diction)

print(next(target))
print(next(target))

Result: 


name
SSN
>>> 

This is how to extract only keys, so we can put them in dedicated list:


diction = {"name" : "Anastasia", "SSN" : 246546}

k_keys = []

target = iter(diction)

for x in range(2):
    k_keys.append(next(target))

print(k_keys)

Result: 


['name', 'SSN']
>>> 

Better option is to not think about number of elements, just use len() function:


diction = {"name" : "Anastasia", "SSN" : 246546}

k_keys = []

target = iter(diction)
print("Len of diction: ", len(diction))

for x in range(len(diction)):
    k_keys.append(next(target))

print(k_keys)

Result: 


Len of diction:  2
['name', 'SSN']
>>> 

Of course, we can do that without iter() and next() functions:


diction = {"name" : "Anastasia", "SSN" : 246546}

k_keys = []

for x in diction.keys():
    print(x)

Result: 


name
SSN
>>> 

Next tutorial will be dedicated to modules.

Python Return Multiple Values

Function can return results to the rest of the script, where other function can take them for further operations.

This simple function will run, but because no further operations will be done, nothing will be printed in shell.


def external(num_1):
    add = num_1 + num_1
    return add

external(10)

But now, results are placed into variable "container" so we can print it on dedicated line, with a little bit of custom report:


def external(num_1):

    add = num_1 + num_1

    return add

container = external(10)

print("Result: ", container)

Result: 


Result:  20
>>> 

Or, you can use function with different arguments on individual lines:


def external(num_1):

    add = num_1 + num_1

    return add

print("Result: ", external(20))
print("Result: ", external(40))
print("Result: ", external(60))

Result: 


Result:  40
Result:  80
Result:  120
>>> 

It's awesome that in Python we can have multiple returns, in this case, "add", and "mul".

Multiple returns are packet into tuple:


def external(num_1):

    add = num_1 + num_1
    mul = num_1 * num_1

    return add, mul

print("Result: ", external(20))
print("Return Type: ", type(external(20)))

Result: 


Result:  (40, 400)
Return Type:  <class 'tuple'>
>>> 

And now we are using individual parts of tuple:


def external(num_1):

    add = num_1 + num_1
    mul = num_1 * num_1

    return add, mul

x, y = external(20)
print("Result of Add: ", x)
print("Result of Mul: ", y)

Result: 


Result of Add:  40
Result of Mul:  400
>>> 

Sometimes we care only about one index from tuple:


def external(num_1):

    add = num_1 + num_1
    mul = num_1 * num_1

    return add, mul

print("Result of Add: ", external(10)[0])
print("Result of Mul: ", external(10)[1])

Result: 


Result of Add:  20
Result of Mul:  100
>>> 

Ok, in next tutorial we will learn about Iterations.

Python Keyboard Arguments

This function will ping some IP/domain with 5 packets. With "-n" number of packets will be part of "ping" instruction.

Pay attention about spaces, they are important while constructing command.

If you are on Linux use "-c", "-n" is for Windows machines.


import os

def custom_ping(ip, packets):
    os.system("ping -n " + str(packets) + " " + ip)

custom_ping("127.0.0.1", 5)

But this is more usable, because we can grab domain and packet number from keyboard without messing around directly with function every time:


import os

def custom_ping(ip, packets):
    os.system("ping -n " + str(packets) + " " + ip)

real_ip = input("Please Enter IP: ")
real_packets = input("Number of packets: ")
    
custom_ping(real_ip, real_packets)

Python Function Arguments

Arguments are data that we pass to functions so that other operations can be done further using what we provided as input.

We will type arguments between parentheses.

This function will just add same number we provided to itself:


def addition(num_1):
    print("Addition:", num_1 + num_1)

addition(5)

Result: 


Addition: 10
>>> 

Sure, you can use multiple arguments, delimited by comma:


def print_them(x, y, z):
    print(x)
    print(y)
    print(z)

print_them(43, 24, "Something")

Result:  


43
24
Something
>>> 

And here, we see very simple calculator:


def calculator(x, y):
    print("Add: ", x + y)
    print("Sub: ", x - y)
    print("Mul: ", x * y)
    print("Div: ", x / y)

calculator(10, 5) 

Result:  


Add:  15
Sub:  5
Mul:  50
Div:  2.0
>>> 

Easy. In next tutorial we will learn how to take arguments from keyboard.

Python Functions

A function is just specific peace of code that will do one thing, and do it well. Think about them as workers that will do only one task.

We can write our own functions, or we can grab them from Internet because they are distributed in dedicated files - modules.

When we install Python, we have at our disposal dedicated modules, with many functions.

Don't forget parentheses and def keyword when creating functions:


def my_function():
    print("Line 1")
    print("Line 2")
    print("Line 3")

my_function()

Result: 


Line 1
Line 2
Line 3
>>> 

Our custom triple() function can call multiple times other functions, in this case we are calling function my_function() three times:


def my_function():
    print("Line 1")
    print("Line 2")
    print("Line 3")

def triple():
    my_function()
    my_function()
    my_function()

triple()

Result:  


Line 1
Line 2
Line 3
Line 1
Line 2
Line 3
Line 1
Line 2
Line 3
>>> 

This is how to create function that will ask for IP so we can Ping it with other function that is in os module:


import os

def ping_something():
    x = input("Enter IP: ")

    os.system("ping " + x)

ping_something()

We can have loops inside functions, too:


def while_in_function():
    x = 0
    while x < 3:
        print(x)
        x = x + 1

while_in_function()

Result:  


0
1
2
>>> 

This is how to have while loop inside function that will have option to stop if you enter "QUIT":


def get_out():
    while True:
        x = input("Enter something: ")
        print(x)

        if x == "QUIT":
            break

get_out() 

Result:  


Enter something: Something
Something
Enter something: Again
Again
Enter something: QUIT
QUIT
>>> 

So far so good. In next tutorial we will learn how to provide some data to functions, so functions can grab it and do something with data we provided.

Python Dictionary Iteration

To grab only keys from dictionary use key() function:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

for x in colors.keys():
    print("Key: ", x)

Result: 


Key:  Color 1
Key:  Color 2
>>> 

Same approach for values, using value() function:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

for x in colors.values():
    print("Value: ", x)

Result:  


Value:  Red
Value:  Yellow
>>> 

Or use items() function to grab key-value pairs:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

print("Key -> Value")
print("-" * 49)

for x, y in colors.items():
    print(x, " -> ", y)

Result:  


Key -> Value
-------------------------------
Color 1  ->  Red
Color 2  ->  Yellow
>>> 

This is how to extract keys and values into dedicated lists:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

key_parts = []
value_parts = []

for x in colors.keys():
    key_parts.append(x)

for y in colors.values():
    value_parts.append(y)

print(key_parts)
print("-" * 59)
print(value_parts)

Result:  


['Color 1', 'Color 2']
-------------------------------
['Red', 'Yellow']
>>> 

Same as above, using only one for loop:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

key_parts = []
value_parts = []

for x, y in colors.items():
    key_parts.append(x)
    value_parts.append(y)

print(key_parts)
print("-" * 59)
print(value_parts)

Result:  


['Color 1', 'Color 2']
-------------------------------
['Red', 'Yellow']
>>> 

Excellent. In next tutorial we will learn about functions.

Python For Loops

For loops are awesome when we need to repeat same operation - they are great for custom reports, for example:


colors = ("red", "blue", "yellow", "green")

for x in colors:
    print(x)

Result: 


red
blue
yellow
green
>>> 

Even better, explain what you are doing:


colors = ("red", "blue", "yellow", "green")

for x in colors:
    print("Elements is: ", x)

Result:  


Elements is:  red
Elements is:  blue
Elements is:  yellow
Elements is:  green
>>> 

For example, we can check if sites are available, with a little bit of pause between checks.

To pause operations, we will import "time" modul to aktivate sleep() function for 2 seconds.

With system() function from "os" module we can run terminal apps just as we use them in terminal or command prompt on machines with Windows.


import os, time

ip = ["127.0.0.1", "google.com"]

for x in ip:
    os.system("ping " + x)
    time.sleep(2)

Now when we know about For Loops, understanding Dictionary Iterations will be easy.

Python Break, Continue

If you need to stop While Loop at specific point, use break when you reach that point.

In this case we are stopping when x reaches number 5. After that point everything stops:


x = 0

while x < 10:
    print(x)
    if x == 5:
        break
    x = x + 1

Result: 


0
1
2
3
4
5
>>> 

What if we need to skip specific things. In that case use continue. Please note - While Loop will run just fine, just specific numbers will be skipped.

In this example, we are skipping over numbers: 3, 5 and 7.


x = 0

while x < 10:
    x = x + 1
    if x == 3:
        continue
    if x == 5:
        continue
    if x == 7:
        continue

    print(x)

Result:  


1
2
4
6
8
9
10
>>> 

For Loops are also fun to work with. We will learn about them in next tutorial.

Python While Loops

While loops are extremely useful when we need specific lines of code to run constantly.

Basically, we need to define a starting point, ending point, and how to jump from one point to another.

Of course, in between those points, some useful part of code need to be executed:


x = 0

while x < 10:
    print("Value of x atm: ", x)
    x = x + 1

Result: 


Value of x atm:  0
Value of x atm:  1
Value of x atm:  2
Value of x atm:  3
Value of x atm:  4
Value of x atm:  5
Value of x atm:  6
Value of x atm:  7
Value of x atm:  8
Value of x atm:  9
>>> 

We will import os module, so we can run application inside our operating system - using Python script.

"x = x + 1" is used to gradually jump from 0 until 3 is reached - it's like a very simple algorithm.

If you run this code, calculator will pop-up 3 times on Desktop. Sure, we can run other apps, not just calc:


import os

x = 0

while x <= 3:
    os.system("calc")
    x = x + 1

In next tutorial, we will learn about Break and Continue options when looping with While Loops.

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