Python Programming
BCC-302
Unit -4
Syllabus
Unit IV
Reading files,
Writing files in python,
Understanding read functions, read(),
readline(), readlines().
Understanding write functions, write()
and writelines()
Manipulating file pointer using seek
Programming, using file operations.
Python - Files I/O
Files are named locations on disk to store related
information. They are 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 the computer is turned
off), we use files for future use of the data by
permanently storing them.
When we want to read from or write to a file, we
need to open it first. When we are done, it needs
to be closed so that the resources that are tied
with the file are freed.
Hence, in Python, a file operation takes place in
the following order:
Open a file
Read or write (perform operation)
Close the file
File Handling in Python
File handling is an important part of any web
application.
Python has several functions for creating, reading,
updating, and deleting files.
The key function for working with files in Python is
the open() function.
The open() function takes two parameters; filename,
and mode.
Example: file_object = open(file_name, access_mode)
Types of Files:
We have two type of files:
1. Text Files: Store data in form of
characters.
Example: text
2. Binary Files: Store data in the form of
bytes.
Example: Audio, Vedio, Pdf.
Example1
Write on File:
age=input(“enter your age:”)
f=open(“data.txt”, ‘w’)
f.write()
f.close()
There are many different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the
file does not exist, The r throws an error if the file does not
exist or opens an existing file without truncating it for reading;
the file pointer position at the beginning of the file.
"a" - Append - Opens a file for appending, creates the file if it
does not exist, The a creates a new file or opens an existing file
for writing; the file pointer position at the end of the file.
"w" - Write - Opens a file for writing, creates the file if it does
not exist. The w creates a new file or truncates an existing file,
then opens it for writing; the file pointer position at the
beginning of the file.
"x" - Create - Creates the specified file, returns an error if the
file exists
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
Python File Open
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:
Example
f = open("demofile.txt", "r")
print(f.read())
If the file is located in a different location, you will have to
specify the file path, like this:
Example
Open a file on a different location:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
Syntax
To open a file for reading it is enough to specify the
name of the file:
f = open("demofile.txt“, mode=‘r’,
encoding=None, errors=None,
newling=None)
<_io.TextIOWrapper name='hello.txt'
mode='a' encoding='cp1252'>
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.
Syntax
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.
Buffering:
Positive Integer value and used to set buffer size
for file
In text mode, buffer size should be 1 or more
than 1
In binary mode, buffer size can be 0
Default size- 4096-8192 bytes.
Error:
Represent how encoding and decoding errors are
to be handled
Cannot be used in binary mode
Some standard values are: strict, ignore, replace
Newline:
Default \n
The close() method
Once all the operations are done on the file,
we must close it through our python script
using the close() method.
Any unwritten information gets destroyed
once the close() method is called on a file
object.
File_handler.close()
What happen when we close a file:- File object
is deleted from memory and file is no more
accessible unless we open it again
What happen when we do not close a file:-
after program execution python garbage
collector will destroy file object and closes file
f= open(“hello.txt”, ‘r’)
print(f)
f.close()
Reading the file
To read a file using the python script, the
python provides us the read() method.
The read() method reads a string from the file.
It can read the data in the text as well as
binary format.
Example
fileptr = open("file.txt","r");
content = fileptr.read();
print(type(content))
print(content)
fileptr.close()
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:
Example
Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))
Looping through the file
fileptr = open("file.txt","r");
for i in fileptr:
print(i) # i contains each line of the file
By looping through the lines of the file, you can
read the whole file, line by line:
READING FROM A TEXT FILE
We can write a program to read the contents of a file. Before reading a
file, we must make sure that the file is opened in “r”, “r+”, “w+” or
“a+” mode.
There are three ways to read the contents of a file:
The read() method
This method is used to read a specified number of bytes of data from a
data file.
The syntax of read() method is:
file_object.read(n).
Consider the following set of statements to understand the usage of
read() method:
>>>myobject=open("myfile.txt",'r')
>>> myobject.read(10)
'Hello ever'
>>> myobject.close()
If no argument or a negative number is specified in read(),
the entire file content is read.
For example
>>> myobject=open("myfile.txt",'r')
>>> print(myobject.read())
Hello everyone Writing multiline strings.
This is the third line
>>> myobject.close()
Run the above code by replacing writelines() with write()
and see what happens. Can we pass a tuple of numbers as
an argument to write lines.
The readline([n]) method
This method reads one complete line from a file where each line terminates with a
newline (\n) character. It can also be used to read a specified number (n) of bytes of
data from a file but maximum up to the newline character (\n).
In the following example, the second statement reads the first ten characters of the
first line of the text file and displays them on the screen.
myobject=open("myfile.txt",'r')
myobject.readline(10) 'Hello ever'
myobject.close()
If no argument or a negative number is specified, it reads a
complete line and returns string.
myobject=open("myfile.txt",'r')
print (myobject.readline())
'Hello everyone\n'
To read the entire file line by line using the readline(),
we can use a loop. This process is known as looping/ iterating
over a file object. It returns an empty string when EOF is
reached.
The readlines() method
The method reads all the lines and returns the lines along
with newline as a list of strings.
The following example uses readlines() to read data from
the text file myfile.txt.
myobject=open("myfile.txt", 'r')
print(myobject.readlines())
['Hello everyone\n', 'Writing multiline strings\n', 'This is
the third line']
myobject.close()
As shown in the above output, when we read a file using
readlines() function, lines in the file become members of a
list, where each list element ends with a newline character
(‘\n’)
Readline and Readlines..
By calling readline() two times, you can
read the two first lines:
Example
Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file,
you can read the whole file, line by line:
Example
Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
SETTING OFFSETS IN A FILE
The functions that we have learnt till now are used to
access the data sequentially from a file. But if we
want to access data in a random fashion, then Python
gives us seek() and tell() functions to do so.
The tell() method :
This function returns an integer that specifies the
current position of the file object in the file. The
position so specified is the byte position from the
beginning of the file till the current position of the file
object.
The syntax of using tell() is: file_object.tell()
The seek() method:
This method is used to position the file object at a
particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by
which the file object is to be moved. reference_point
The seek() method:
It can have any of the following values:
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference point is 0, i.e. the
offset is counted from the beginning of the file. For
example, the statement fileObject.seek(5) will
position the file object at 5th byte position from the
beginning of the file.
Example of Seek and tell methods:
print(“Example to implement seek and tell")
fileobject=open("testfile.txt","r+")
str=fileobject.read()
print(str)
print("Initially, the position of the file object is: ",fileobject. tell())
fileobject.seek(0)
print("Now the file object is at the beginning of the file”: ,fileobject.tell())
fileobject.seek(10)
print("We are moving to 10th byte position from the beginning of file")
print("The position of the file object is at", fileobject.tell())
str=fileobject.read()
print(str)
Example for Seek operation 2
fi=open("text.txt",'w')
fi.write("How do you\n know the p\narameters of
the concerning details and\n other things to be
done for the departmental\n")
fi.close()
fi = open("text.txt", "r")
# the second parameter of the seek method is by
default 0
fi.seek(30)
# now, we will print the current position
print(fi.tell())
print(fi.readline())
fi.close()
Assignments:-
1. Write a Python program to read an entire text file.
2. Write a Python program to read first n lines of a file.
3. Write a Python program to append text to a file and
display the text.
4. Write a Python program to read last n lines of a file.
5. Write a Python program to read a file line by line
and store it into a list.
6. Write a Python program to read a file line by line
store it into a variable.
7. Write a Python program to read a file line by line
store it into an array.
8. Write a python program to find the longest words.
9. Write a Python program to count the number of
lines in a text file.
10. Write a Python program to count the frequency of
words in a file.
11. Write a Python program to get the file size of a plain
file.
12. Write a Python program to write a list to a file.
13. Write a Python program to copy the contents of a file
to another file .
14. Write a Python program to combine each line from
first file with the corresponding line in second file.
15. Write a Python program to read a random line from a
file.
16. Write a Python program to assess if a file is closed or
not.
17. Write a Python program to remove newline characters
from a file.
18. Write a Python program that takes a text file as input
and returns the number of words of a given text file.
Note: Some words can be separated by a comma with no
space.
19. Write a Python program to extract characters from
various text files and puts them into a list.
Close Files
It is a good practice to always close the file
when you are done with it.
Example
Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Python File Write
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
Example
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())
Python Delete File
To delete a file, you must import the OS module, and
run its os.remove() function:
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
Check if File exist:
To avoid getting an error, you might want to check if
the file exists before you try to delete it:
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Deleting files/folder using Python
import os
if os.path.exists("demofile.txt
"):
os.remove("demofile.txt")
else:
print("The file does not
exist“)
import os
os.rmdir("myfolder")
Delete a File
To delete a file, you must import the OS module,
and run its os.remove() function:
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
Delete Folder
To delete an entire folder, use the os.rmdir()
method:
Example
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Exceptions
An exception can be defined as an abnormal
condition in a program resulting in the
disruption in the flow of the program.
Whenever an exception occurs, the program
halts the execution, and thus the further code
is not executed.
Therefore, an exception is the error which
python script is unable to tackle with.
Python provides us with the way to handle the
Exception so that the other part of the code
can be executed without any disruption.
Common Exceptions
1.ZeroDivisionError: Occurs when a
number is divided by zero.
2.NameError: It occurs when a name is
not found. It may be local or global.
3.IndentationError: If incorrect
indentation is given.
4.IOError: It occurs when Input Output
operation fails.
Exception handling in python
If the python program contains suspicious
code that may throw the exception, we must
place that code in the try block.
The try block must be followed with the
except statement which contains a block of
code that will be executed if there is some
exception in the try block.
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
try except else
We can also use the else statement with the
try-except statement in which, we can place
the code which will be executed in the
scenario if no exception occurs in the try
block.
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d“ %c)
except Exception:
print("can't divide by zero")
else:
print("Hi I am else block")
Output
Enter a:10
Enter b:2
a/b = 5
Hi I am else block
Points to remember
We can declare multiple exceptions in the
except statement since the try block may
contain the statements which throw the
different type of exceptions.
We can also specify an else block along with
the try-except statement which will be
executed if no exception is raised in the try
block.
The statements that don't throw the exception
should be placed inside the else block.
Example
try:
#this will throw an exception if the file doesn'
t exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
The finally block
We can use the finally block with the try block
in which, we can place the important code
which must be executed before the try
statement throws an exception.
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
finally:
print("finally block is always
executed")
Declaring multiple exceptions
try:
#block of code
except (<Exception 1>,<Exception 2>,<Ex
ception 3>,...<Exception n>)
#block of code
else:
#block of code
Example
try:
a=10/0;
except ArithmeticError,StandardError:
print "Arithmetic Exception"
else:
print "Successfully Done"