15) FilesGUI | PDF | Matrix (Mathematics) | Computer File
0% found this document useful (0 votes)
4 views

15) FilesGUI

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

15) FilesGUI

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

CS114 - Fundamental of Programming

Dr. Nazia Perwaiz


nazia.perwaiz@seecs.edu.pk

vision.seecs.edu.pk

Note: Various contents in this presentation have been taken from different books, lecture notes, and the web. These solely belong to their
owners, and are here used only for clarifying various educational concepts. Any copyright infringement is not intended.
Week-13-14 – Recap
● List is a collection which is ordered and changeable. Allows duplicate
members.

● Tuple is a collection which is ordered and unchangeable. Allows


duplicate members.

● Set is a collection which is unordered, unchangeable (except adding and


removal of items), and unindexed. No duplicate members.

● Dictionary is a collection which is ordered and changeable. No


duplicate members.
File Handling
Python File Handling
Steps for file handling
File is a named location on disk to store related information
It is used to permanently store data in non-volatile memory
In Python, a file operation take place in the following order:

1. Open a file Read or write


2. Perform operation
3. Close the file
Types of Files
Text File: Text file usually we use to store character data. For example, test.txt
Binary File: The binary files are used to store binary data such as images, video files, audio
files, etc.

• "t" - Text - Default value. Text mode

• "b" - Binary - Binary mode (e.g. images, media files)


Opening a File
Python provides a built-in function open() to read or write a file
Pass file path and access mode to the open(file_path, access_mode) function.
# Opening the file
fp = open('sample.txt')
# or # "r" for read, and "t" for text are the default values
fp = open('sample.txt', 'rt')
# Opening the file by giving absolute path
fp = open("D:\\myfiles\sample.txt", "rt")
Opening a File
There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
Three Ways to Read a File
There are three different ways to read in a file:

1. Read the whole file in as one big long string


myFile.read()

2. Read the file in one line at a time


myFile.readline()

3. Read the file in as a list of strings (each is one line)


myFile.readlines()

8
Entire Contents into One String
>>> info = open("hours.txt")
>>> wholeThing = info.read()

>>> wholeThing
'123 Susan 12.5 8.1 7.6 3.2\n456 Brad 4.0 11.6 6.5 2.7
12\n789 Jenn 8.0 8.0 8.0 8.0 7.5\n'
our input file
it’s literally one hours.txt
123 Susan 12.5 8.1 7.6 3.2
giant string! 456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5

9
One Line at a Time
>>> info = open("hours.txt")
>>> lineOne = info.readline()
>>> lineOne
'123 Susan 12.5 8.1 7.6 3.2\n'
>>> lineTwo = info.readline()
'456 Brad 4.0 11.6 6.5 2.7 12\n' our input file
hours.txt
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5

10
As a List of Strings
>>> info = open("hours.txt")
>>> listOfLines = info.readlines()
>>> listOfLines
['123 Susan 12.5 8.1 7.6 3.2\n',
'456 Brad 4.0 11.6 6.5 2.7 12\n',
'789 Jenn 8.0 8.0 8.0 8.0 7.5\n']
our input file
hours.txt
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5

11
Using for Loops to Read in Files
for loops are great for iterating

With a list, the for loop iterates over…


◦ Each element of the list (in order)
Using a range(), the for loop iterates over…
◦ Each number generated by the range (in order)
And with a file, the for loop iterates over…
◦ Each line of the file (in order)

12
A Better Way to Read One Line at a Time
Instead of reading them manually, use a for loop to iterate through the file
line by line

>>> info = open("hours.txt")


>>> for eachLine in info:
print(eachLine)

123 Susan 12.5 8.1 7.6 3.2


456 Brad 4.0 11.6 6.5 2.7 12 our input file
789 Jenn 8.0 8.0 8.0 8.0 7.5 hours.txt
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5

13
Exercise: 1
Write a program that goes through a file and reports the longest
line in the file

Example Input File: caroll.txt


Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch.

Example Output:
>>> longest.py
longest line = 42 characters
the jaws that bite, the claws that catch,
14
Exercise- 1 Solution
def main():
input = open("carroll.txt")
longest = ""
for line in input:
if len(line) > len(longest):
longest = line

print("Longest line =", len(longest))


print(longest)
main()

15
Writing to an Existing File
To write to an existing file, add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
This is first line of sample.txt
This is second line of sample.txt
fp = open("sample.txt", “a") This is third line of sample.txt
fp.write(“The newly added text ") The newly added text

fp = open("sample.txt", “w")
fp.write(“The newly added text")
The newly added text
Python GUI
Python - GUI Programming (Tkinter)
Python provides various options for developing graphical user interfaces (GUIs). Most important
are listed below:

Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would
look this option in this tutorial.
wxPython: This is an open-source Python interface for wxWindows http://wxpython.org.
JPython: JPython is a Python port for Java, which gives Python scripts seamless access to Java
class libraries on the local machine http://www.jython.org.
Python - GUI Programming (Tkinter)
Tkinter allows you to develop desktop applications. It’s a very good tool for GUI
programming in Python.
• Tkinter is a good choice because of the following reasons:
• Easy to learn.
• Use very little code to make a functional desktop application.
• Layered design.
• Portable across all operating systems including Windows, macOS, and Linux.
• Pre-installed with the standard Python library.
Python GUI Program
● Tkinter is a Python library used to create GUI (Graphical User Interface) applications.

Task 1:
● Import Tkinter package, Create a window, Set its title

import tkinter as tk

# Create instance (This instance represents the main window or the root of the GUI application.)
parent = tk.Tk()

# Add a title (Title function is used to sets the title of the window )
parent.title("-Welcome to Python tkinter ")

# The GUI application is started with the function mainloop(), It is the main event loop that keeps the
GUI application running until the user closes the window or exits the application.
parent.mainloop()
Python GUI Program
Temperature Converter application using Tkinter:
Python GUI Program
This application has a title (of window), label, an entry, and a button:
Python GUI Program
First, import the tkinter modules

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showerror
Python GUI Program
Second, create the root window and set its configurations:

# root window
root = tk.Tk()
root.title('Temperature Converter')
root.geometry('300x70')
root.resizable(False, False)
Python GUI Program
Third, define a function that converts a temperature from Fahrenheit to Celsius:

def fahrenheit_to_celsius(f):
""" Convert fahrenheit to celsius
"""
return (f - 32) * 5/9
Python GUI Program
Fourth, create a frame that holds form fields:

frame = ttk.Frame(root)

Fifth, define an option that will be used by all the form fields:

options = {'padx': 5, 'pady': 5}


Python GUI Program
Sixth, define the label, entry, and button. The label will show the result once you click the
Convert button:
# temperature label
temperature_label = ttk.Label(frame, text='Fahrenheit')
temperature_label.grid(column=0, row=0, sticky='W', **options)

# temperature entry
temperature_entry = ttk.Entry(frame, textvariable=temperature)
temperature_entry.grid(column=1, row=0, **options)
temperature_entry.focus()
Python GUI Program
Sixth, define the label, entry, and button. The label will show the result once you click the
Convert button:
# convert button
convert_button = ttk.Button(frame, text='Convert')
convert_button.grid(column=2, row=0, sticky='W', **options)
convert_button.configure(command=convert_button_clicked)

# result label
result_label = ttk.Label(frame)
result_label.grid(row=1, columnspan=3, **options)
Python GUI Program
Convert Button:

def convert_button_clicked():
""" Handle convert button click event
"""
try:
f = float(temperature.get())
c = fahrenheit_to_celsius(f)
result = f'{f} Fahrenheit = {c:.2f} Celsius'
result_label.config(text=result)
except ValueError as error:
showerror(title='Error', message=error)
Python GUI Program
Finally, place the frame on the root window and
run the mainloop() method:

frame.grid(padx=10, pady=10)
root.mainloop()
Exercise – Using Matrix
Write a Python program to read a matrix from the console and print the sum for each
column. As input from the user, accept matrix rows, columns, and elements separated by a
space (each row).
Solution
def read_matrix():
rows, cols = map(int, input("Enter the number of rows and columns separated by a space:
").split())
matrix = []
for _ in range(rows):
row = list(map(int, input("Enter the elements for a row separated by a space: ").split()))
matrix.append(row)
return matrix
Solution
def column_sum(matrix):
rows = len(matrix)
cols = len(matrix[0])
sums = [0] * cols

for j in range(cols):
for i in range(rows):
sums[j] += matrix[i][j]

return sums
Solution
# Read the matrix from the console
matrix = read_matrix()

# Calculate the sum for each column


column_sums = column_sum(matrix)

# Print the sum for each column


print("Sum for each column:")
for i, col_sum in enumerate(column_sums):
print(f"Column {i + 1}: {col_sum}")
Solution (Explained)
The read_matrix() function prompts the user to enter the number of rows and columns of the
matrix. It then reads the elements of the matrix row by row and appends them to the matrix
list.

The column_sum() function takes the matrix as input and calculates the sum for each column.
It initializes an empty list called sums to store the sums for each column. It iterates over each
column and row of the matrix, accumulating the values for each column in the sums list.

After reading the matrix from the console using read_matrix(), the program calls
column_sum(matrix) to calculate the sum for each column and store the result in the
column_sums list.

Finally, the program prints the sum for each column using a loop. It iterates over the
column_sums list, printing the column number (index + 1) and its corresponding sum.

You might also like