Module:4: Modules and Packages, Libraries, Files and GUI
Module:4: Modules and Packages, Libraries, Files and GUI
import math_operations
result_add = math_operations.add(5, 3)
result_subtract = math_operations.subtract(10, 4)
result_multiply = math_operations.multiply(2, 6)
result_divide = math_operations.divide(10, 2)
print(result_add) # Output: 8
print(result_subtract) # Output: 6
print(result_multiply) # Output: 12
print(result_divide) # Output: 5.0
Packages
together.
Creating a Package
Let's go through the process of creating a package named my_package with two
modules (module1.py and module2.py) in PyCharm and then using the package in a
main.py file.
Step 1: Open PyCharm
Open PyCharm and create a new project or open an existing one where you want to
create the package.
Step 2: Create a New Directory for the Package
Right-click on the project folder in the Project Explorer pane on the left side of the
PyCharm window.
Select "New" and then choose "Directory."
Name the directory my_package and click "OK."
Step 3: Create Python Modules
• Inside the my_package directory, create two Python modules named module1.py and
module2.py.
• Right-click on the my_package directory.
• Select "New" and then choose "Python File."
• Name the first file module1.py and click "OK."
• Repeat the process to create the second file named module2.py.
Step 4: Add Python Code to the Modules
Edit the module1.py and module2.py files and add some Python code to them.
# my_package/module1.py
def func1():
print("Function 1 from module 1")
# my_package/module2.py
def func2():
print("Function 2 from module 2")
Step 5: Create __init__.py
• Right-click on the my_package directory (not the modules) and select "New" ->
"Python File."
• Name the file __init__.py and click "OK."
• Your package structure should now look like this:
my_package/
__init__.py
module1.py
module2.py
Step 6: Using the Package
• Create a new Python file named main.py in the project folder (not inside the
my_package directory).
• Inside main.py, import and use the functions from the package.
# main.py
import random
import secrets
import numpy as np
The open() function is the primary tool for file handling in Python. It allows you to open a
file and get a file object that you can use to perform file operations. The basic syntax of the
open() function is:
file = open('filename', 'mode’)
Here, 'filename' is the name of the file you want to open, and 'mode' specifies the purpose
for which you want to open the file (e.g., read, write, append, etc.).
Some common file modes are:
'w': Write mode. The file is opened for writing. If the file already exists, its
content will be truncated. If the file doesn't exist, a new file will be created.
'a': Append mode. The file is opened for writing, but data is appended to the
end of the file. If the file doesn't exist, a new file will be created.
'b': Binary mode. Used in combination with other modes for binary files (e.g.,
read(size): Reads size number of characters from the file. If size is not specified, it reads
readlines(): Reads all lines from the file and returns them as a list.
Once you have opened the file, you can perform various operations:
read(size): Reads size number of characters from the file. If size is not specified, it reads
content = file.read()
print(content)
Once you have opened the file, you can perform various operations:
readlines(): Reads all lines from the file and returns them as a list.
lines_list = file.readlines()
print(lines_list)
Writing to a File:
The write() function in Python is used to write data to a file that has been opened in write or
append mode. It allows you to add content to the file, either creating a new file or
overwriting the existing content, depending on the file mode.
file.write(data)
Parameters:
data: The data to be written to the file. It can be a string or a bytes object (in binary mode).
Return Value:
The write() function does not return anything. It writes the data to the file and moves the file
pointer to the end of the written data.
Example: Writing to a File in Write Mode
# Open a file in write mode
with open("example.txt", "w") as file:
file.write("Hello, this is an example.\n")
file.write("We are writing to a file in Python.\n")
In this example, we open a file named "example.txt" in write mode using the open()
function with mode "w". We use a with statement to automatically close the file
after we are done writing.
We then use the write() method of the file object to write two lines of text to the
file. The \n at the end of each line represents a newline character to add a line break
between the two lines.
After running this code, the "example.txt" file will contain the following content:
Hello, this is an example.
We are writing to a file in Python.
Example: Writing to a File in Append Mode
# Open a file in append mode
with open("example.txt", "a") as file:
file.write("This is an additional line appended to the file.\n")
In this example, we open the same "example.txt" file, but this time, we use the
append mode "a" in the open() function. This mode allows us to add data to the end
of the existing content without overwriting it.
We use the write() method to append an additional line to the end of the file.
After running this code, the "example.txt" file will have the following content:
Hello, this is an example.
We are writing to a file in Python.
This is an additional line appended to the file.
It is important to note that the write() function does not automatically add
newline characters, so if you want to write multiple lines, you need to include
\n to separate them. Additionally, be cautious when using the write function
in write mode ("w"), as it will overwrite the existing content of the file. If you
want to preserve the existing content and add new data, use append mode
("a").
Manipulating file pointer using seek
To manipulate the file pointer using seek, you'll need to open the file in an
appropriate mode that allows reading or writing. Then, you can use the
seek() method to move the file pointer to the desired position within the file.
Here's how you can do it in Python:
Opening a file and manipulating the file pointer for reading:
# Open the file in read mode ('r')
with open('example.txt', 'r') as file:
# Move the file pointer to the 10th character from the beginning of the file
file.seek(10)
def demonstrate_seek(file_path):
with open(file_path, 'r+') as file:
# Read the initial content of the file
print("Initial content:")
print(file.read())
# Seek backward 20 characters from the end of the file and write
file.seek(-20, 2)
file.write("Going back 20 characters.\n")
# Reset the file pointer to the beginning and read the final content
file.seek(0, 0)
print("Final content:")
print(file.read())
if __name__ == "__main__":
# Seek to the end of the file (whence=2) and write
file.seek(0, 2)
file.write("End of the file.\n")
# Seek backward 20 characters from the end of the file and write
file.seek(-20, 2)
file.write("Going back 20 characters.\n")
# Reset the file pointer to the beginning and read the final content
file.seek(0, 0)
print("Final content:")
print(file.read())
if __name__ == "__main__":
file_path = "example.txt"
with open(file_path, "w") as file:
file.write("0123456789ABCDEFGHIJ")
demonstrate_seek(file_path)
Introduction to Tkinter and Python Programming
❑ Tkinter is a standard Python library used for creating graphical user interfaces
(GUI).
❑ It provides a set of widgets and functions that allow developers to build
interactive and visually appealing desktop applications.
❑ Tkinter is based on the Tcl/Tk GUI toolkit, which is widely used and
well-supported across different platforms.
❑ Python, on the other hand, is a versatile and popular programming language
known for its simplicity, readability, and extensive libraries.
❑ Combining Python with Tkinter allows developers to build cross-platform GUI
applications efficiently.
Why use Tkinter?
• Easy to learn and use: Tkinter's straightforward API and simple syntax make it easy
for beginners to grasp and start building GUI applications quickly.
• Cross-platform: Tkinter is available on most operating systems, including Windows,
macOS, and Linux, ensuring that your application can run on multiple platforms
without modification.
• Widely supported: Being a part of the Python standard library, Tkinter is
well-maintained and actively supported, ensuring compatibility with future Python
versions.
• Large community: The popularity of Python and Tkinter means that you can find
numerous tutorials, resources, and community support online.
Getting Started with Tkinter:
Tkinter is included in the Python standard library, so you don't need to install any
additional packages.
Importing Tkinter:
To begin, import the tkinter module:
import tkinter as tk
root.mainloop()
Example 2: Tkinter Window with Button and Label
import tkinter as tk
def on_button_click():
label.config(text="Button clicked!")
root = tk.Tk()
root.title("Tkinter Button Example")
root.mainloop()
Example 3: Tkinter Entry and Output Example
import tkinter as tk
def show_output():
output_label.config(text="Your name is: " + entry.get())
root = tk.Tk()
root.title("Tkinter Entry Example")
root.mainloop()
Example 4: Check Button and Radio Button
import tkinter as tk
checkbutton1 = tk.Checkbutton(root, text="Option 1",
def show_options(): variable=var1)
selected_options = "Selected options: " checkbutton2 = tk.Checkbutton(root, text="Option 2",
if var1.get(): variable=var2)
selected_options += "Option 1 " checkbutton3 = tk.Checkbutton(root, text="Option 3",
if var2.get(): variable=var3)
selected_options += "Option 2 "
if var3.get(): checkbutton1.pack()
selected_options += "Option 3 " checkbutton2.pack()
output_label.config(text=selected_options) checkbutton3.pack()