[go: up one dir, main page]

0% found this document useful (0 votes)
15 views62 pages

Files

The document provides an overview of file handling in Python, including types of files, file operations, and methods for reading, writing, and managing files. It also covers command line arguments, exception handling, and practical examples such as copying files, counting words, and validating voter age. Key concepts include file modes, attributes, and various file methods for manipulating data.

Uploaded by

bhuvanasumathi7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views62 pages

Files

The document provides an overview of file handling in Python, including types of files, file operations, and methods for reading, writing, and managing files. It also covers command line arguments, exception handling, and practical examples such as copying files, counting words, and validating voter age. Key concepts include file modes, attributes, and various file methods for manipulating data.

Uploaded by

bhuvanasumathi7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

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, Voter’s age validation, Marks range validation


File Handling
• File is a named location on the system storage which records data for
later access.
• It is a collection of data stored on a secondary storage device like
hard disk. They can be easily retrieved when required.
• Python supports two types of files.
• Binary file
• Text file
• Binary file: A binary file is a file which may contain any type of data,
encoded in binary form for computer storage and processing purpose.
• It can be processed sequentially or randomly depending on the needs of
the application

Text file: A text file is a stream of characters that can be sequentially


processed by a computer in forward direction.
In a text file, each line of data ends with a new line \n character.
Each file ends with a special character called the End of File (EOF) marker.
File Operations
• Opening a File
• Reading from a file
• Writing a file
• Closing a file
Opening a File
• The contents of a file can be read by opening the file in read mode
using the built-in open() function.
• Two arguments that are mainly needed by the open() function.
• File name or file path
• Mode in which the file is opened.
Syntax:
Fileobject = open (filename[,access mode])

Where,
File_name🡪 It is a string value which contains the name of the file to
access
Access_mode🡪 Determines the mode (read, write, append, etc.) in
which the file has to be opened.
Modes of File
• r🡪default mode for opening a file in read only format
• rb🡪read only purpose in binary format
• r+🡪Both read and write in text format
• rb+🡪Read and Write in binary format
• w🡪 write in text format
• wb🡪write only purpose in binary format
• w+🡪Reading and Writing in text format
• wb+🡪Reading and Writing in binary format
• a🡪appending the data to the file
• ab🡪appending the data in binary format
• a+🡪 Both appending and reading data to and from the file
• ab+🡪appending and reading data in binary format
• The text mode returns strings when reading from the file.
• The binary mode returns bytes and this mode is used when dealing
with non-text files like image or exe file.
Example
# Open file in read mode, the default mode:
>>>file = open(“sample.txt”)
>>>file = open(“sample.txt”,’w’) #write mode
>>>file = open(“sam.bmp”,’rb+’) # Read & files in binary mode
>>> file = open(“sample.txt”,mode=‘r’,encoding=‘utf-8’)
File Object Attributes
Attribute Returns
file.name File Name
file.mode The access mode to open file (r, w,r+,etc.,)
file.closed It returns True, if closed and False otherwise
Example
p=open("sample.txt",'w') Output:
print("File Name:",p.name) File Name: sample.txt
print("Closed or Opened:",p.closed) Closed or Opened: False
print("Mode of opening file:",p.mode) Mode of opening file: w
Writing to a file
The write() is used to write a string or sequence of bytes. It returns the
number of characters written in the file.
Open a file 🡪write ‘w’,append ‘a’
If the file already exists, the file will be overwritten
Syntax:
fileObject.write(str)
Example
p=open("sample1.txt","w") Output:
p.write("Information Technology \n")
p.write("Velammal College of
Engineering and Technology\n")
p.write("Madurai")
p.close()
Read Data from a File
Methods Explanation
Read([size]) It returns the specified number of characters from the
file
Readline() Returns the next line of the file
Readlines() Reads all the lines as list of strings in file
f=open("sample1.txt","r")
f.read(5)
'Infor'
f.read(6)
'mation'
f.read()
' Technology \nVelammal College of Engineering and Technology\nMadurai'
f.read()
''
f=open("sample1.txt","r")
f.readline()
'Information Technology \n'
f.readline()
'Velammal College of Engineering and Technology\n'
f.readlines()
['Madurai']
Closing a file
• In close() method, a file object flushes all information and closes the
file object.
• No more updations can be performed
• Syntax:
fileObject.close()
Example
p=open("sample1.txt","w")
print("Name of file:",p.name)
p.write("Information Technology \n")
p.write("Velammal College of Engineering and Technology\n")
p.write("Madurai")
p.close()
print("File Closed")
Output
Name of file: sample1.txt
File Closed
Appending Data to a file
• To append a new text to the existing file , we have to reopen the file
on append mode with ‘a’.
Syntax:
fileObject.open(“filename”,”a”)

Where, a🡪append mode


Example
f=open("sample.txt","a")
f.write("Chennai\n")
f.write("Tamilnadu")
f.close()
Renaming and Deleting a file
• Rename()
• Rename an existing file by a new file name.
• Two arguments🡪 old file name and new file name
• Syntax:
import os
os.rename(old_filename,new_filename)
Example:
import os
os.rename("sample.txt","program.txt")
• Remove() method:
• To delete an existing file, use the remove() method that can be called from
the os module.
• Syntax:
os.remove(filename)
Example:
import os
os.remove("program.txt")
Directories
• A directory is a collection of files and sub files.
• Python has the os module which provides us with many useful
methods to work with directories
• Making a new directory
• Current Working Directory
• Changing Directory
• Removing Directory
• List directories and files
Making a new directory
• Mkdir() method is used to make new directories
Syntax:
os.mkdir(“newdir”)
Code:
import os
os.mkdir("testdir")
Current Working Directory
• The getcwd() method displays the current directory in which we are
working
Syntax:
os.getcwd()
Code:
import os
print(os.getcwd())
Removing directory from the file
• rmdir()deletes or removes directory.
Syntax:
import os
os.rmdir(“dir_name”)
Code:
import os
os.rmdir("testdir")
List directories and files
• This method lists all files and sub directories inside a given directory.
• Syntax:
import os
os.listdir()
Changing Directory
• The chdir() method in python’s os module is used to change the
current directory.
Syntax:
os.chdir(“dir_name”)
File Methods
• Flush()
• Fileno()
• Isatty()
• Seek()
• Tell()
• Truncate()
• Write()
• Writelines()
• Next()
Flush()
• Flush method will force out any unsaved data that exists in a program buffer to
the actual file.
• The data will be copied from the program buffer to the operating system buffer
(file). It is implicitly called by the close() function
• Syntax: fileObject.flush()
Code:
p=open("file2.txt","wb")
print("Name of the file:",p.name)
p.flush()
p.close()
Output:
Name of the file: file2.txt
Fileno()
• The fileno() method returns the integer file descriptor which is used to request I/O
operations from the operating system
• Syntax: fileObject.fileno()
• Code:
p=open("file.txt","wb")
print("Name of the file:",p.name)
filedes=p.fileno()
print("File Descriptor:",filedes)
p.close()
Output:
Name of the file: file.txt
File Descriptor: 3
Isatty()
• The isatty() method returns TRUE, if the file is connected with a terminal device to atty
device, else it returns FALSE.
• Syntax: fileObject.atty()
• Code:
p=open("file.txt","wb")
print("Name of the file:",p.name)
res=p.isatty()
print("File Descriptor:",res)
p.close()
Output:
Name of the file: file.txt
File Descriptor: False
Seek()
• In Python, seek() function is used to change the position of the File Handle to a
given specific position. File handle is like a cursor, which defines from where the
data has to be read or written in the file.
• Syntax: f.seek(offset, from_what), where f is file pointer
• Parameters:
Offset: Number of positions to move forward
from_what: It defines point of reference.
• 0: sets the reference point at the beginning of the file

• 1: sets the reference point at the current file position

• 2: sets the reference point at the end of the file


Tell()
• tell() returns the current position of
the file pointer from the beginning
of the file.
Example:
f = open("demofile.txt", "r")
# points at the start
Hello World
print(f.tell()) Educative
Output:
0
f = open("demofile.txt", "r")
f.seek(4)
print(f.readline())
Output:
Output
o World
truncate()
The truncate() method in Python resizes the file to a specified size. If no size is given, it uses the current file
position.
The truncate() method is declared with a file object, as
follows:

import os
p=open("sam.txt","a")
file_size=os.path.getsize("sam.txt")
print(file_size)
p.truncate(40)
file_size2=os.path.getsize("sam.txt")
print(file_size2)
p.close()
File.write(str)
• The write() method writes a string to the given file.
• Syntax: fileObject.write(str)
• Code:
Fileobj=open(“sample.txt”,”w”)
Fileobj.write(“New line gets added \n”)
Fileobj.close()
Output:
Writelines()
• This method writes a sequence of strings into a file.
• The sequence can be any iterable object which produces a list of strings.
• Syntax: fileObject.writelines(sequence)
• Where, sequence🡪sequence of string
• Code:
import os
p=open("sam.txt","a")
seq=["\n","College of\n","Engineering and Technology"]
p.writelines(seq)
p.close()
Output
Next()
• The next() method is used in a file when it acts as an iterator in a loop.
• It will be called repeatedly.
• Syntax: fileObject.next()
Format Operator
Command Line Arguments
• Python command line • Input()🡪STRING
arguments are input parameters • Another way to accept the
passed to the script/program inputs other than inpu()
when executing them.
• Inputs will be passed to the
• Almost all programming programs as an arguments from
language provide support for COMMAND PROMPT
command line arguments.
• sys module
Execute:
Write Program
Save with .py extension
Open Command Prompt
Change the path to where the program is
being saved
Py filename.py arg1 arg2 arg3…..
• The function python sys module provides us to interact with the
interpreter.
• The python sys module provides access to any command-line
arguments via the sys.argv.
• 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 i.e. script name
import sys
a=int(sys.argv[1])
b=int(sys.argv[2])
c=a+b
print(c)
Output:
import getopt
Python getopt module import sys
args='-a -b -c -foo -d bar a1 a2'.split()
• Python getopt module helps you parse optlist,args=getopt.getopt(args,'abc:d')
command-line options and arguments. print('option list',optlist)
getopt.getopt(args,options,[long_options]) print('Arguments',args)
• Args: This is the argument list to be parsed.
args='-a -b -cfoo -d bar a1 a2'.split()
• Options: This is the string of option letters that the script optlist,args=getopt.getopt(args,'abc:d:')
wants to recognize, with options that require an argument
print('option list',optlist)
should be followed by a colon (:)
print('Arguments',args)
• Long_options: This is optional parameter and if specified,
must be a list of strings with the names of the long
options, which should be supported. Long options, which
require an argument should be followed by an equal
sign(‘=‘). To accept only long_options should be an empty
string
Problems Given
1. Copy from one file to another
2. Word count
3. Longest word
Copy from one file to another
print("Title of the program: Copy of one file to another")
f1=input("Enter the source file to be copied")
f2=input("Enter the destination file")
f1=open(f1,"r")
f2=open(f2,"w")
for i in f1.readlines():
f2.write(i)
f1.close()
f2.close()
Output
==============================
=== RESTART:
C:\Users\abikasi\Desktop\lg.py
==============================
===
Title of the program: Copy of one file
to another
Enter the source file to be copied
sample.txt
Enter the destination filefile2.txt
1 file copied
Words Count
f1="file1.txt"
with open(f1,"r") as f:
content=f.read()
print("File1 Content: \n",content)
words=content.split()
word_count = len(words)
print("Total number of words in the file:",word_count)
Output
File1 Content:
Information Technology
Velammal College of Engineering and Technology
Madurai
Total number of words in the file: 9
Longest Word
f1="file1.txt"
with open(f1, "r") as f:

wordsList = f.read().split()
longestWordLength = len(max(wordsList, key=len))
# Here, we are checking all the words whose length is equal to that of the
longest word
result = [text for text in wordsList if len(text) == longestWordLength]

print("The following are the longest words from a text file:")


print(result)

f.close()
Output
File1 Content:
Information Technology
Velammal College of Engineering and Technology
Madurai

The following are the longest words from a text file:


['Information', 'Engineering']
Implementing real-time/technical applications using Exception handling

1. Divide by zero error


2. Voter’s age validity
3. Student mark range validation
Divide by zero error
a=18.0
b=0
try:
result=a/b
except ZeroDivisionError:
print("Division by zero!")
age=eval(input("Enter your age"))
if(age<0):
raise ValueError
except(ValueError):
print("Value Error:Invalid Age Value.")
else:
if(age>18):
print("Eligible to vote")
else:
print("Not eligible to vote")

finally:
print("Thank you, you have successfully checked the voting eligibility")
Student mark range validation

• Print(“Tilte of the program”)


• In try block,
• Get the mark of any course subject
• If mark > 90, Print “Your Grade is O – Outstanding Peroformer”
• Elif mark between 90 & 80, Print “Your Grade is A+ - Excellent performer”
• Elif mark between 80 & 70 , Print “Your grade is A – Very Good Performer”
• Elif mark between 70 & 60, Print “Your grade is B+ -Good Performer”
• Elif mark between 60 & 50, Your grade is B – Average”
Except ValueError as err:
Print(err)
• Finally:
• Print(“Thank you, you have successfully verified about your PSPP course”)

You might also like