0% found this document useful (0 votes)
6 views

5 Python Files

Uploaded by

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

5 Python Files

Uploaded by

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

FILES

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
File Handling
• Before you can read or write a file, you have to open it using Python's
built-in open() function.
• This function creates a file object, which would be utilized to call
other support methods associated with it
• Open() takes two parameters; filename, and mode.
• There are four different methods (modes) for opening a file:

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
4 modes for opening a file

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
• In addition you can specify if the file should be handled as binary or
text mode

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
• To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
• The code above is the same as:
f = open("demofile.txt", "rt")
• Because "r" for read, and "t" for text are the default values, you do
not need to specify them.
• Note: Make sure the file exists, or else you will get an error.

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
• Assume we have the following file, located in the same folder as
Python:
Demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
• To open the file, use the built-in open() function.
• The open() function returns a file object, which has a read() method
for reading the content of the file:

f = open("demofile.txt")
print(f.read())

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
• If the file is located in a different location, you will have to specify the
file path, like this:

f = open("D:\\welcome.txt")
print(f.read())

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Read Only Parts of the File
• By default the read() method returns the whole text, but you can also
specify how many characters you want to return:

#Return the 5 first characters of the file:


f = open("demofile.txt")
print(f.read(5))

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
readline()

• You can return one line by using the readline()method

# Reads one line of the file


f = open("demofile.txt")
print(f.readline())

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
readlines()
• Return all lines in the file, as a list where each line is an item in the list
object:

f = open("demofile.txt", "r")
print(f.readlines())

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
• By looping through the lines of the file, you can read the whole file,
line by line:
• f = open("demofile.txt", "r")
for x in f:
print(x)

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Close Files
• It is a good practice to always close the file when you are done with it.

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Note: You should always close your files, in some cases, due to
buffering, changes made to a file may not show until you close the file.

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
#Print the file line by line.At the end of the file, readline returns the
empty string
f=open(“oldfile.txt”,”r”)
while(true):
text=f.readline()
if(text==“”):
break
print(text)
f.close()

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Write to an Existing File

• To write to an existing file, you must add a parameter to the open()


function

• "a" - Append - will append to the end of the file


• "w" - Write - will overwrite any existing content

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
• Open the file "demofile2.txt" and append content to the file
• f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
• Open the file "demofile3.txt" and overwrite the content:
• f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Create a New File
• To create a new file in Python, use the open() method, with one of
the following parameters:
• "x" - Create - will create a file, returns an error if the file exist
• "a" - Append - will create a file if the specified file does not exist
• "w" - Write - will create a file if the specified file does not exist

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
• Create a file called "myfile.txt":
f = open("myfile.txt", "x")
• Result: a new empty file is created!

• Create a new file if it does not exist:


f = open("myfile.txt", "w")

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Copy the contents of one file to another
f1=open(“t1.txt”)
f2=open(“t2.txt”,”w”)
while(True):
txt=f1.readline()
if txt==“”:
break
f2.write(txt)
f1.close()
f2.close()
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
Writing Variables
• The argument of write has to be a string, so to put other values in a
file, we have to convert them to strings first
• The easiest way is to use str function
x=52
f.write(str(x))

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Writing Variables
• Alternative way is to use the format operator %.
• When applied to integers,% is modulus operator. But when the first
operand is a string,% is the format operator
• The first operand is the format string, and the second operand is a
tuple of expressions. The result is a string that contains the values of
the expressions, formatted according to the format string
• Format sequence “%d” means that the first expression in the tuple
should be formatted as an integer. d stands for decimal
• %f,%s etc

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Format operator
cars=52
txt=“%d” % cars
print(txt)
Output-> ‘52’
• Format sequence can appear anywhere in the format string
txt=“In July, we sold %d cars” % cars
=> ‘In July, we sold 52 cars’

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Format String
• The no. of expressions in the tuple has to match the number of
format sequences in the string
“%d %d %d” % (1,2)
TypeError:not enough arguments for format string
• Types of the expressions have to match the format sequences
“%d” % ‘dollars’
TypeError: Illegal argument type for built-in operation

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Format String
• We can specify the number of digits as part of the format sequence
• The number after the % sign is the minimum number of spaces the
number will take up. If the value provided takes fewer digits, leading
spaces are added
“%6d” % 62 => ‘ 62’
• If the number of spaces is negative, trailing spaces are added
“%-6d” % 62 => ‘62 ’

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Format String
• For floating point numbers, we can also specify the number of digits
after the decimal point
“%6.2f” % 4.3 => ‘ 4.30’

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
• To put values into a file, you have to convert them into strings
• F.write(str(12.3))
• F.write(str([1,2,3]))
• The problem is that when you read the value back, you get a string.
The original type information has been lost
• F.readline() => ‘12.3[1,2,3]’
• You cant even tell where one value ends and the next begins
• The solution is pickling, it preserves data structures

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Pickling
• Python pickle module is used for serializing and de-serializing python
object structures.
• The process to converts any kind of python objects (list, dict, etc.) into
byte streams (0s and 1s) is called pickling or serialization or flattening
or marshalling.
• We can converts the byte stream (generated through pickling) back
into python objects by a process called as unpickling.

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Pickle a simple list
import pickle
mylist = ['a', 'b', 'c', 'd']
fh=open('datafile.txt', 'wb')
pickle.dump(mylist, fh)

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Unpickle a simple list
import pickle
f = open ("datafile.txt", "rb")
emp = pickle.load(f)
print(emp)

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Pickling
Prons:
• Comes handy to save complicated data.
• Easy to use, lighter and doesn’t require several lines of code.
• The pickled file generated is not easily readable and thus provide
some security.
Cons:
• Languages other than python may not able to reconstruct pickled
python objects.
• Risk of unpickling data from malicious sources.
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
EXCEPTIONS

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Exceptions
• Whenever a runtime error occurs, it creates an exception
• Usually the program stops and prints an error message
• For eg. Divide by zero creates an exception
>>>print(55/0)
ZeroDivisionError:integer division or modulo
• Accessing a nonexistent list item
>>>a=[]
>>>print(a[5])
IndexError:list index out of range
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
Exceptions
• Accessing a key that is not in the dictionary
>>>b={}
>>>print(b[“What”])
• KeyError:what
• Trying to open a non existent file
>>>f=open(“Idontexist”,”r”)
• IOError:[Errno 2] No such file or directory:’Idontexist’
• Trying to print an undefined variable
>>>print(x)
NameError: name 'x' is not defined
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
• In each case , the error message has two parts: the type of error
before colon and specifics about the error after the colon
• Normally python prints a traceback of where the program was
• Sometimes we want to execute an operation that could cause an
exception, but we don’t want the program to stop
• We can handle the exception using the try and except statements

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
try…except
filename=input(“Enter file name:”)
try:
f=open(filename)
except IOError:
print(“There is no file named”,filename)
• Try statement executes the statements in the first block. if no
exceptions occur, it ignores the except statement. if an exception of
type IOError occurs,it executes the statements in the except block

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Many Exceptions
• You can define as many exception blocks as you want, e.g. if you want
to execute a special block of code for a special kind of error:
#Print one message if the try block raises a NameError and another for
other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
• try:
print(x)
except (NameError,KeyError,IndexError):
print("Variable x is not defined")

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
else
• You can use the else keyword to define a block of code to be executed
if no errors were raised:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
finally
• The finally block, if specified, will be executed regardless if the try
block raises an error or not.
• This can be useful to close objects and clean up resources:

try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
Example
#Try to open and write to a file that is not writable:
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()

#The program can continue, without leaving the file object open.
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
Raise an exception
• As a Python developer you can choose to throw an exception if a
condition occurs.
• To throw (or raise) an exception, use the raise keyword.

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Raise an exception
#Raise an error and stop the program if x is lower than 0:
x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
#To Handle raised exception
x=-1
try:
if x<0:
raise Exception(" Sorry, no numbers below zero")
except:
print("Negative Number")

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki
Raise an exception
• The raise keyword is used to raise an exception.
• You can define what kind of error to raise, and the text to print to the
user.
#Raise a TypeError if x is not an integer:
x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

Prof. Jincy Kuriakose, Dept. of Information Technology, GEC


Idukki

You might also like