Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
37 views

PYTHON PROG-Module-3-1

This document covers file handling, packaging, and debugging in Python, detailing methods for reading, writing, and deleting text and CSV files. It also discusses exception handling, including the use of try-except blocks and assert statements for debugging. Additionally, it explains the concepts of modules, packages, and libraries in Python, along with instructions for using pip and converting Python files into executable files.

Uploaded by

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

PYTHON PROG-Module-3-1

This document covers file handling, packaging, and debugging in Python, detailing methods for reading, writing, and deleting text and CSV files. It also discusses exception handling, including the use of try-except blocks and assert statements for debugging. Additionally, it explains the concepts of modules, packages, and libraries in Python, along with instructions for using pip and converting Python files into executable files.

Uploaded by

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

PYTHON PROGRAMMING

MODULE-3
File handling, Packaging and debugging
Method for text file handling in python:
• open() used to open file in python.
• read() used to read the content from file in python.
• readline() used to read one line at a time from file in python.
• write() used to read the content from file in python.
• close() used to close file in python.
• Modes: “r” for reading , “w” for writing, “a” for appending
Opening a text file in python:
open() used to open file in python.
File must be present in same folder or else path need to
be specified.

1. File_pointer_variable = open("test.txt", “w”)

2. with open("file1.txt", "r") as File_pointer_variable:


Reading a text file in python:
read() used to read the content from file in python.
1. #open a file in read mode
file1 = open(“data.txt“, “r”)
read_content = file1.read()
print(read_content)
file1.close()

2. with open(“data.txt", "r") as file1:


read_content = file1.read()
print(read_content)
Writing to text file in python:
write() used to read the content from file in python.
1] #open a file in write mode
file1 = open(“data.txt“, “w”)
file1.write(“Write here something.\n”)
file1.write(“File operations are useful\n”)
file1.close()

2] with open(“data.txt", “w") as file1:


file1.write(“Write something here\n”)
file1.write(“Write something here\n”)
Deleting text file:
• Operating system module “os” need to import.
• Use remove() from os module.

import os
os.remove(“data.txt”)
csv file handling in python:
• The CSV (Comma Separated Values) format is a common and
straightforward way to store tabular data or spreadsheets.
• To represent a CSV file, it should have the .csv file extension.
• Each value in a line is separated by Delimiter ( , ).
• For csv file operations, csv module need to import.
• r/w/a operations are performed through some object/variable.
Functions in csv module in python:
• csv.reader() function is used to create a reader object.
• csv.writer() function is used to create a writer object.
• csv.DictReader() function is used to create a dictionary
reader object.
• writerow() function is then used to write single rows to the CSV
file. (1D data in form of list by-default)
• writerows() function is then used to write multiple rows to the
CSV file. (2D data in form of nested list by-default)
Reading a csv file as list in python:
1] import csv
file1 = open(“data.csv“, “r”)
read_content = csv.reader(file1,delimiter=‘ , ’)
print(read_content) #gives me object not values
for row in read_content:
print(row)
file1.close()
Reading a csv file as list in python:
2] import csv
with open(“data.csv”, “r”) as file1:
read_content = csv.reader(file1,delimiter=“ , ”)
print(read_content) #gives me object not values
for row in read_content:
print(row)
Reading a csv file as dictionary in python:
Entries of the first row are the dictionary keys and entries in the
other rows are the dictionary values.
1] import csv
file1 = open(“data.csv“, “r”)
read_content = csv.DictReader(file1,delimiter=‘ , ’)
print(read_content) #gives me object not values
for row in read_content:
print(dict(row))
file1.close()
Reading a csv file as dictionary in python:
2] import csv
with open(“data.csv”, “r”) as file1:
read_content = csv.DictReader(file1,delimiter=“ , ”)
print(read_content) #gives me object not values
for row in read_content:
print(dict(row))
Writing to csv file in python: (List input)
import csv
List1=[[1,2,3,4],[5,6,7,8]]
with open(“data.csv”, “w”, newline=“”) as file1:
write_content = csv.writer(file1,delimiter=“ , ”)
write_content.writerrow([1,2,3,4])
write_content.writerrow([1,2,3,4])
write_content.writerrows(List)
Writing to csv file in python: (Dictionary input)
#writerows() is not applicable.
import csv
with open('players.csv', 'w', newline="") as file2:
names = ["Name","Age"] #list
writer=csv.DictWriter(file2, fieldnames=names)
writer.writeheader()
writer.writerow({"Name": "A", "Age":11}) #1 key:value pair
writer.writerow({"Name": "B", "Age":22 })
writer.writerow({"Name": "C", "Age":33 })
writer.writerow({"Name":"D","Age":44})
writer.writerow({"Name": "E", "Age": 55})
Python Exception:
• Runtime errors are called exceptions/logical errors.
OR unexpected events that occur at runtime are called exceptions.
• It occurs due to incorrect implementation of logic within the program.
• Such events disrupt/interrupt the normal flow of the program.
• Errors are usually beyond the control of the interpreter.
• Whenever runtime errors occur, Python creates an exception object.
• Exceptions can be caught and handled by the program itself using
exception handling syntax.
Python Errors(X) and Exceptions (√):
Error / Exception Cause of Error
AssertionError (√) Raised when an assert statement fails.
ModuleNotFoundError (√) Raised when the imported module is not found.
IndexError (√) Raised when the index of a sequence is out of range.
KeyError (√) Raised when a key is not found in a dictionary.
NameError (√) Raised when a variable is not found in local or global scope.
RuntimeError (X) Raised when an error does not fall under any other category.
SyntaxError (X) Raised by parser when syntax error is encountered.
IndentationError (X) Raised when there is incorrect indentation.
TypeError (√) Raised when operation is applied to an object of incorrect
type.
ValueError (√) Raised when a function gets an argument of correct type but
improper value.
ZeroDivisionError (√) Raised when divisor is zero indivision or modulo operation.
Exception handling:
• Mechanism through which we can handle exception is called “Exception
Handling”.
• Exception Handling-> try, except, else, finally block (Ended with colon).
• syntax:
try:
# code that may cause exception (suspicious code)
except <exception_name> :
# code will run only when exception occurs within try block
else: #optional block
# code executes only when no exceptions (except block wont execute at that time)
finally: #optional block
# code always executed
print("code before exception")
try: Output:
numerator = 10
Code before exception
denominator = 0
result = numerator/denominator Error: Denominator cannot be 0.
print(result) <class 'Exception’>
except Exception as obj:
print("Error: Denominator cannot be 0.") <class 'ZeroDivisionError’>
print(Exception) division by zero
print(type(obj), “\n”,obj)
finally: This is finally block.
print("This is finally block.") code After exception
print("code After exception")
print("code before exception")
try: Output:
even_numbers = [2,4,6,8]
print(even_numbers[5]) Code before exception
except ZeroDivisionError: Index Out of Bound.
print("Denominator cannot be 0.")
except IndexError: This is finally block.
print("Index Out of Bound.") code After exception
finally:
print("This is finally block.")
print("code After exception")
Python Assert Statement:
• Assert statement has a condition or expression which is supposed to be always true.

• If condition is true, then program does nothing and moves to the next line of code.

• If the condition is false assert halts the entire program and gives an AssertionError.

• It is also a debugging tool as it halts the program as soon as an error occurs and displays it.

• assert keyword is used to create assert statement.

• Syntax for using Assert in Pyhton: assert <condition>

assert <condition>, “<error message>”

• Assert statement can also have a condition and a optional error message enclosed within
quotes. If the condition is not satisfied assert stops the program and
gives AssertionError along with the error message.
Python Assert Statement:
• Assert statement has a condition or expression which is supposed to be always true.
• If condition is true, then program does nothing and moves to the next line of code.
• If the condition is false, assert stops the entire program and gives an AssertionError.
• It is also a debugging tool as it halts the program as soon as an error occurs and
displays it.
• assert keyword is used to create assert statement.
• Syntax for using Assert in Pyhton: assert <condition>
assert <condition>, “<error message>”
• Assert statement can also have a condition and a optional error message enclosed
within quotes. If the condition is not satisfied assert stops the program and
gives AssertionError along with the error message.
Output:
code before
print("code before")
Enter password: abcd
val=input("Enter password:") Traceback (most recent call last):
assert val=="Abcd“ File "<main.py>", line 3, in <module>
print("System 1 unlocked") AssertionError

print("System 2 unlocked")
Output:
print("System 3 unlocked")
code before
print("code after") Enter password: Abcd
System 1 unlocked
System 2 unlocked
System 3 unlocked
code after
print("code before exception") Output:
try: code before exception
Enter a password: Abcd
password = input("Enter a password: ")
Correct password
assert password == "Abcd" This is finally block.
except: code After exception
print("Wrong password")
else: Output:
code before exception
print("Correct password")
Enter a password: abcd
finally: Wrong password
print("This is finally block.") This is finally block.
code After exception
print("code After exception")
Python pip: (PIP:Package Installer for Python)
• It is the package manager for Python that allows you to install,
update, and manage Python libraries (packages) from the Python
Package Index (PyPI).
• pip is like as an app store for Python libraries.
• Use all prompt in command line:
Check if pip install pip --version OR pip
Install package pip install <name>
Uninstall package pip uninstall <name>
Check list of installed packages pip list
Conversion of .py file into .exe file:
• Open command prompt in the folder where .py file located.(mandatory)
• Install “pyinstaller” module (one time install), command is:
pip install pyinstaller
• Now give command (multiple files): pyinstaller <filename.py>
• For single files, give command: pyinstaller --onefile <filename.py>
• Doing some more formatting, Install “auto-py-to-exe” module (one time
install), command is:
pip install auto-py-to-exe
• Now give command: auto-py-to-exe
• Giving custom icon to exe file, file format should be .ico (not .jpeg, .png)
Modules, Packages, Libraries in python:
Modules in Python:
• A module is a single Python file (.py) containing Python code.
• It can include functions, classes, and variables that you can reuse in
other programs.
• Syntax: import <module_name>
import <module_name> as <short_name>

Packages in python:
• A package is a collection of modules (many python file) organized in
directories (folders) with an __init__.py file.
• Syntax:
from <package_name> import <particular_module>
Modules, Packages, Libraries in python:
Libraries in Python:
• A library is a collection of modules and packages.
• Libraries are typically larger and more feature-rich than packages or
modules.
• Syntax: import <library_name>
import <library_name> as <short_name>

• Summary:
Module: A single page.
Package: A book containing multiple pages.
Library: A book store with many books.
Example of importing Module:
# file name: myfile.py # file name: mymodule.py
import mymodule as mymod person={“Name”: “Shaggy”, “Age”: 30}
#from mymodule import person
mymod.say_hello(“Willy") def say_hello(name):
mymod.say_bye(“Wonka") return print(f"Hello, {name}!")
print(person[“Name”]) def say_bye(name):
Output: return print(f“Bye, {name}!")

Hello, Willy!
Bye, Wonka!
Shaggy

You might also like