UNIT –5.pptxpython for engineering students

SabarigiriVason 15 views 43 slides Mar 03, 2025
Slide 1
Slide 1 of 43
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43

About This Presentation

python


Slide Content

UNIT – 5 FILES, MODULES, PACKAGES

Files and exception: text files, reading and writing files, format operator; command line arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs: word count, copy file.

FILES File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g. hard disk). Since, random access memory (RAM) is volatile which loses its data when computer is turned off, we use files for future use of the data. A collection of data or information that has a name, called the filename. Almost all information stored in a computer must be in a file.

TYPES OF FILES Data files Text files Program files Directory files

File O perations In Python, a file operation takes place in the following order. Open the file Read or write (Data Updating - perform operation) Close the file

1. Open a file Syntax file_object = open(“filename”, “mode”) file_object is the variable to add the file object mode – tells the interpreter and developer which way the file will be used.

FILE OP E N I N G M OD E

Open a file Example : f = open(“test.txt”) # open file in current directory (or) f = open(“C:/Python3.3/sample.txt”) # specifying full path

f = open(“test.txt”) # equivalent to ‘r’ or ‘ rt ’ f = open(“ test.txt”,“w ”) # write in text mode f = open(“homepg.bmp”,“ r+b ”) # read and write in binary mode

2. Reading and writing files In general, there are two methods to manipulate the files, they are given below : a ) write() b ) read()

write() Method This method writes any string to an open file. It is important to note that Python strings can have binary data and not just text. The write() method does not add a newline character (‘\n’) to the end of the string. Syntax fileObject.write (string)

Example # Open a file f= open(“ sam1.txt ”, “ wb ”) f.write ( “I will try my best.\ nGod is always with me!!\n”); # Close opened file f.close () I will try my best. God is always with me !! sam1.txt

read() Method This method reads a string from an open file. It is important to note that Python strings can have binary data apart from text data. Count parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file. Syntax fileObject.read ((count))

Example-1 # Open a file f= open(“ sam1.txt ”, “ r+ ”) str = f.read (10); print( str ) # Close opened file f.close () I will try my best. God is always with me !! s ample.txt Output : I will try

readLine () function # Open a file f= open(“ sam1.txt ”, “ r+ ”) print( f.readLine ()) # Close opened file f.close () I will try my best. God is always with me !! s ample.txt Output : I will try my best.

3. Close a file Syntax file_object .close() This method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another file

Example # Open a file f= open(“ sam1.txt ”, “ r+ ”) str = f.read (10); print( str ) # Close opened file f.close () I will try my best. God is always with me !! s ample.txt Output : I will try

Looping over a file object Example : file = open(“samtext.txt”, “r”) for line in file: print line The user want to read – or return – all the lines from a file in a more memory efficient, and fast manner, user can use the loop over method. The advantage to using this method is that the related code is both simple and easy to read. Welcome to Akshaya college By 2017 Batch Output Welcome to Akshaya college By 2017 Batch

With Statement Example : with open(“testfile.txt”) as file: data = file.read () print( data.upper ()) The user can also work with file objects using the with statement. It is designed to provide much cleaner syntax and exceptions handling when you are working with code. Advantages If any files opened will be closed automatically after you are done. This leaves less to worry about during cleanup. Welcome to Akshaya college By 2017 Batch Output WELCOME TO AKSHAYA COLLEGE BY 2017 BATCH

Splitting Lines in a Text File Example : with open(“ hello.text ”, “r”) as f: data = f.readlines () for line in data: words = line.split () print words This function that allows you to split the lines taken from a text file. What this is designed to do, is split the string contained in variable data whenever the interpreter encounters a space character. Welcome to Akshaya college By 2017 Batch Output [“Welcome”, “to”, “ Akshaya ”, “By”, “2017”, “Batch”]

The file Object Attributes Attribute Description file.closed Returns true if file is closed, false otherwise. file.mode Returns access mode with which file was opened. file.name Returns name of the file. file.softspace Returns false if space explicitly required with print, true otherwise.

FILE MANIPULATIONS There are two major methods are play the vital role, they are: ( i ) tell() (ii) seek() The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file. The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved. From Reference position Beginning of a file 1 Current position of a file 2 End of a file

Example : Welcome to Akshaya college By 2017 Batch Output Read String is : Welcome to Current file position : 10 Again read String is : Welcome to # Open a file fo = open(“sam1.txt”, “r+”) str = fo.read (10); print (“Read String is : ”, str ) # Check current position position = fo.tell (); print (“ Current file position : ”, position) # Reposition pointer at the beginning once againposition = fo.seek (0, 0); str = fo.read (10); print (“Again read String is : ”, str ) # Close opend file fo.close ()

R enaming a File rename() Method The rename() method takes two arguments, the current filename and the new filename. Syntax os.rename ( current_file_name , new_file_name ) Example import os # Rename a file from test1.txt to test2.txt os.rename ( “test1.txt”, “test2.txt” )

D eleting a File remove() Method This method is used to delete files by supplying the name of the file to be deleted as the argument. Syntax os.remove ( file_name ) Example import os # Rename a file from test1.txt to test2.txt os.remove ( “test1.txt”)

Command-line options and arguments Python provides a getopt module that helps you parse command-line options and arguments. >>> python test.py arg1 arg2 arg3 The Python sys module provides access to any command-line arguments via the sys.argv . This serves two purposes, they are: sys.argv is the list of command-line arguments. len ( sys.argv ) is the number of command-line arguments. Here sys.argv [0] is the program ( ie ) script name.

ERRORS AND EXCEPTIONS Errors or mistakes in a program are often referred to as bugs. They are almost always the fault of the programmer. The process of finding and eliminating errors is called debugging. Errors can be classified into three major groups: a ) Syntax errors b ) Runtime errors c ) Logical errors

HANDLING EXCEPTIONS An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program’s instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error. When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits. Python provides two very important features to handle any unexpected error in the Python programs and to add debugging capabilities in them. Exception Handling Assertions

Standard Exceptions

A ssertions An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program. The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised. Syntax : assert Expression[, Arguments]

Example : def KelvinToFahrenheit (Temperature): assert (Temperature >= 0),“Colder than absolute zero!” return ((Temperature-273)*1.8)+32 print KelvinToFahrenheit (273) print int ( KelvinToFahrenheit (505.78)) print KelvinToFahrenheit (-5 ) Output 32.0 451 Traceback (most recent call last): File “test.py”, line 9, in print KelvinToFahrenheit (-5) File “test.py”, line 4, in KelvinToFahrenheit assert (Temperature >= 0),”Colder than absolute zero!” AssertionError : Colder than absolute zero!

Logic – HandlingExceptions try : You do your operations here ; ...................... except ExceptionI : If there is ExceptionI , then execute this block . except ExceptionII : If there is ExceptionII , then execute this block ....................... else: If there is no exception then execute this block. Syntax :

A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. The else-block is a good place for code that does not need the try: block’s protection. Important points about syntax:

Example : try: fh = open(“ testfile ”, “r”) fh.write (“This is my test file for exception handling!!”) except IOError : print “Error: can’t find file or read data” else: print “Written content in the file successfully ” Output Error : can’t find file or read data

Advantages of exception handling : It separates normal code from code that handles errors. Exceptions can easily be passed along functions in the stack until they reach a function which knows how to handle them. The intermediate functions don’t need to have any error-handling code. Exceptions come with lots of useful error information built in – for example, they can print a traceback which helps us to see exactly where the error occurred.

MODULES A module allows you to logically organize the Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.

Example : import fibo This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. Using the module name you can access the functions: fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 fibo.fib2(100) [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] fibo.__name __ ‘ fibo ’ If you intend to use a function often you can assign it to a local name: fib = fibo.fib fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377

import statement You can use any Python source file as a module by executing an import statement in some other Python source file. Syntax : import module1[, module2[,... moduleN ]

T he from...import Statement Python’s from statement lets you import specific attributes from a module into the current namespace. Syntax : from modname import name1[, name2[, ... nameN ]]

PACKAGES A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub- subpackages , and so on . Consider a file Pots.py available in Phone directory. This file has following line of source code: def Pots(): print “I’m Pots Phone” Similar way, we have another two files having different functions with the same name as above:

Phone/Isdn.py file having function Isdn() Phone/G3.py file having function G3() Now, create one more file __ init__.py in Phone directory: Phone/__ init__.py To make all of your functions available when you’ve imported Phone, you need to put explicit import statements in __ init__.py as follows: from Pots import Pots from Isdn import Isdn from G3 import G3 After you add these lines to __ init__.py , you have all of these classes available when you import the Phone package. # Now import your Phone Package. import Phone Phone.Pots () Phone.Isdn () Phone.G3() Output I’m Pots Phone I’m 3G Phone I’m ISDN Phone

ILLUSTRATIVE PROGRAMS Program 1: Word Count # Word Count file=open(“C:/python27/python operators.txt”,”r +”) wordcount ={} for word in file.read ().split(): if word not in wordcount : wordcount [word ] = 1 else: wordcount [word ] += 1 for k,v in wordcount.items (): print k, v

Program 2: Copy Files # Copy Files from shutil import copyfile while True: print (“Enter ‘x’ for exit.”) sourcefile = input(“Enter source file name: “) destinationfile = input(“Enter destination file name : “) if sourcefile == ‘x’: break else: copyfile ( sourcefile , destinationfile ) print (“File copied successfully!”)
Tags