Amreli } Russian Call Girls Ahmedabad - Phone 8005736733 Escorts Service at 6...
Module2-Files.pdf
1. PYTHON APPLICATION PROGRAMMING -
18EC646
MODULE 2
FILES
Prof. Krishnananda L
Department of ECE
Govt Engineering College
Mosalehosahalli, Hassan
2. FILE HANDLING IN PYTHON
Till now, we were taking the input from the keyboard/console and writing it back to the console to
interact with the user.
Sometimes, it is not enough to only display the data, or the data to be displayed may be very large or
information to be given by user for processing is too large (Ex: students’ info in a class). In such
cases, standard I/O is not feasible. Also, since video RAM is volatile, it is impossible to recover the
programmatically generated data again and again.
The file handling plays an important role when the data needs to be stored permanently. Also, if the
output or result of the program has to be used for some other purpose later, it has to be stored
permanently. Hence, reading/writing from/to files are essential requirement of programming.
A file is a named location on disk to store related information. We can access the stored information
(non-volatile) after the program termination.
A file is some information/data which stays in the computer’s secondary storage devices.
File handling is an important part of any web application.
2
3. CONTD..
Python treats file differently as text or binary.
A text file is basically a sequence of lines containing alphanumeric characters
Database files are binary files, specifically designed to read and write through database software
Each line of a Text file is terminated with a special character, called the EOL or End of Line
characters like comma {,} or newline character. It ends the current line and tells the interpreter a
new one has begun.
Python has several functions for creating, reading, updating, and deleting files.
Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘n’) in Python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine-understandable binary language.
A file operation can be done in the following order.
• Open a file
• Read or Write - Performing operation
• Close the file
3
4. OPENING FILES
When we want to read or write a file, we first must open the file.
Opening the file communicates with operating system, which knows where the data for each file is stored.
The file being opened should be stored in the same folder that you are in when you start Python
When you open a file, you are asking the operating system to find the file by name and make sure the file
exists.
• This is done with the open() function
• open() returns a “file handle” - a variable used to perform operations on the file
• The open() function takes two parameters; filename, and access mode.
• There are four different modes for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
4
Other variations are:
rb – read mode, binary file
r+ - open file for both read
and write (doesn’t
overwrite the existing file)
W+- open file for both
write and read.
(Overwrites the existing
file)
5. CONTD..
Syntax:
handle = open(“filename”, “mode”)
filename is a string
mode is also a string and optional for read operation.
Handle- is a reference to an object of file class which is
required for all further operations on files
Ex:
>>>fhand=open(“demo.txt”, ‘r’)
>>>print (fhand)
>>> if fhand:
print (“file opened successfully”)
Output: <_io.TextIOWrapper name='demo.txt' mode='r'
encoding='cp1252'>
file opened successfully
>>>f = open("demo.txt")
Same as
>>>f = open("demo.txt", "r")
To open a file for reading, it is enough
to specify the name of the file without
mode being specified.
Note: Default python file
access mode is ‘r’ with
open()
5
Note: A text file has
newlines at the end of each
line
6. • >>>fh=open("demo1.txt", 'r')
• >>>print (fh)
• Traceback (most recent call last):
• File "D:/18EC646/file1.py", line 1, in <module>
• fhand=open("demo1.txt", 'r')
• FileNotFoundError: [Errno 2] No such file or directory: 'demo1.txt‘
Note: If the file does not exist, open will fail with a traceback
and you will not get a handle to access the contents of the file:
We can use try-except block of codes to take care of this
CONTD..
6
Note: When a file gets opened
successfully, then a file object is
returned. This is known as file
handle
• A file opening may cause an error due to:
File may not exist in the specified path (when we try to read a file)
File may exist, but we may not have a permission to read/write a file
File might have got corrupted and may not be in an opening state
7. READING FROM FILES
I.
fp=open("d:/18ec646/demo.txt")
for x in fp:
print (x)
Output:
hello and welcome to
python programming
Another way to read a text file uses a list
comprehension to load the file line-by-line into a
list:
II.
>>> lines = [k.strip() for k in open('demo.txt')]
>>>print (lines)
## load the file line-by-line into a list
Output:
['hello and welcome to', 'python programming']
III. # when file size is small
>>>f = open('demo.txt')
>>>s=f.read()
>>>print (s)
## load entire file into a string
Output:
hello and welcome to
python programming
Note: If the file is located in a different location other
than the present working directory, you will have to
specify the file path
7
A file handle open for read can be treated as a sequence
of strings where each line in the file is a string in the
sequence
We can use for statement to iterate through the file
#### count the number of lines in the file
## use a for loop
fh = open('demo.txt')
count = 0
for k in fh:
count = count + 1
print('Line Count:', count)
Output:
Line Count: 2
8. CONTD..
V. you can read the whole file into one string
using the read method on the file handle.
## read the whole file into a string
## Illustration of string slicing for a file
f = open('demo.txt')
inp = f.read()
print(len(inp))
print(inp[:15])
print ()
print (inp[20:])
Output:
42
hello and welco
python programming
IV. “””to read an existing file and print
its contents”””
>>>f1 = open("demo.txt", "r")
>>> print(f1.read())
Output:
hello and welcome to
python programming
Note: The open() function returns a
file object, which has
a read() method for reading the
content of the file:
read() : Returns the read
bytes in form of a string.
Reads n bytes, if n is not
specified, reads the entire
file.
8
Note: A text file can be
thought of as a sequence
of lines. To break the file
into lines, there is a
special character that
represents the end of the
line called as ‘newline
character’ (n)
9. CONTD..
## to read first 20 characters of
the file and print
f = open("demo1.txt", "r")
content= f.read(20)
print (type(content))
print (“first 20 characters are:”)
print(content)
f.close()
Output:
<class ‘str’>
first 20 characters are:
hello and welcome to
###You can return one line of the file by
###using the readline() method:
f = open("demo.txt", "r")
print(f.readline())
f.close()
Output:
This session is exclusively to deal with
###Read two lines of the file:
f = open("demo1.txt", "r")
line1=f.readline()
line2=f.readline()
print(line1)
print(line2)
Output:
This session is exclusively to deal with
file handling in python
Note: It is a good practice to
always close the file after the
operation
Note: By calling readline() two
times, you can read the two first
lines:
9
10. 10
### using readlines() method
fileptr = open("demo4.txt","r")
#stores all the data of the file into the variable
content
content = fileptr.readlines()
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
### file slicing example
f = open('demo4.txt‘, ‘r’)
s=f.read()
print ("the file contents are:")
print (s)
print ()
print ("total no of characters in the file are:", len(s))
print ("beginning characters of the file are:", s[:20])
print ("file contents between 30 and 80 characters: ", s[30:71])
CONTD..
Output:
['python is a easy-to-usen', 'open source, high-level,
object-orientedn', 'programming language']
Output:
the file contents are:
python is a easy-to-use
open source, high-level, object-oriented
programming language
total no of characters in the file are: 86
beginning characters of the file are: python is a easy-to
file contents between 30 and 70 characters: source, high-level,
object-oriented
progr
Note: It returns the list of the lines till the
end of file(EOF) is reached.
11. 11
MODIFYING FILE POINTER POSITIONS
Python provides the tell() method which is used to print
the byte number at which the file pointer currently
exists.
fileptr = open(“demo4.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() retu
rns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
In real-world applications, we need to
change the file pointer location externally
since we may need to read or write the
content at various locations. Python provides
the seek() method which enables us to
modify the file pointer position
<file-ptr>.seek(offset[, from])
The seek() method accepts two parameters:
offset: It refers to the new position of the file
pointer within the file.
from: It indicates the reference position from
where the bytes are to be moved. If it is set to 0,
the beginning of the file is used as the reference
position. If it is set to 1, the current position of
the file pointer is used as the reference position.
If it is set to 2, the end of the file pointer is used
as the reference position.
12. 12
""“ use of seek() method
Python file method seek() sets the file's
current position at the offset.
"""
f = open("demo4.txt", "r+")
print ("Name of the file: ", f.name)
line = f.readline()
print("Read Line: %s" % (line))
# Again set the pointer to the beginning
f.seek(0, 0)
line = f.readline()
print ("Read Line: %s" % (line))
### seek relative to the current position
f.seek(0, 1)
line = f.readline()
print ("Read Line: %s" % (line))
### seek relative to the current position
f.seek(0, 1)
line = f.readline()
print ("Read Line: %s" % (line))
### Reposition to 10th index position from the
beginning
f.seek(10, 0)
line = f.readline()
print ("Read Line: %s" % (line))
# Close opened file
f.close()
Output:
Name of the file: demo4.txt
Read Line: python is a easy-to-use
Read Line: python is a easy-to-use
Read Line: open source, high-level, object-oriented
Read Line: programming language
Read Line: a easy-to-use
13. WRITING TO FILES
To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the existing file
(file pointer at the end of the file)
"w" - Write - will overwrite any existing content; else
opens a new file to write (file pointer at the beginning of
the file)
• Open a file with ‘write’ mode using a file handler. Use
print statement with file argument to write each line
into the file and close the file
• Example script file:
• f = open(‘demo1.txt', 'w')
• print(‘ hello and welcome to ', file=f)
• print(‘Python application programming ', file=f)
• print (‘This class is about File handling in Python’,
file=f)
• f.close()
### to illustrate appending new text at the end of
#existing file
f = open("demo1.txt", "a")
f.write("Now the file has more content!")
f.write (" This is to append text at the end of file")
f.close()
#open and read the file after appending:
## to check
f = open("demo1.txt", "r")
print(f.read())
13
Note: If the file handler variable is used to assign some
other file object (using open() function), then Python
closes the previous file automatically
Note: write() method doesn’t add new line character
14. EXAMPLE
“”” illustration of file write and read
operations in different ways
Creating a file for writing
entering data in file using list data”””
print("creating demo3.txt file in write mode")
file1 = open("demo3.txt", "w")
## create a list with strings as data
L = ["This is Bangalore n", "This is Paris n",
"This is London n"]
# Writing data to a file
file1.write("Hello and welcome n")
file1.writelines(L)
file1.close()
file1 = open("demo3.txt", "r")
print("Output of the file after reading: ")
print()
print(file1.read())
print("Output of Readline function is ")
print(file1.readline())
Output:
creating demo3.txt file in write mode
Output of the file after reading:
Hello and welcome
This is Bangalore
This is Paris
This is London
Output of Readline function is
Hello and welcome
14
15. EXAMPLE
• """ to read a list of temperature values from a file
called temp.txt, convert them to Fahrenheit and
put the computed values to new file ftemp.txt"""
• f1 = open('ftemp.txt', 'w')
• temp= [k.strip() for k in open('temp.txt')]
• print (“Temperature in Celsius are:”)
• print (temp)
• print(“Temperature in Fahrenheit are:”)
• for t in temp:
• t1= int(t)*9/5+32
• print (t1, file=f1)
• print (t1)
• f1.close()
Output:
Temperature in Celsius are:
['23', '45', '7', '80', '98', '100']
Temperature in Fahrenheit are:
73.4
113.0
44.6
176.0
208.4
212.0
15
16. CREATING A 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
• Create a file called "myfile.txt":
• f = open("myfile.txt", "x") # a new empty file is created
• Create a new file if it does not exist:
f = open("myfile1.txt", "w")
16
17. FILE/DIRECTORY OPERATIONS
• To delete/rename a file, you must import the OS
module:
import os
os.remove("demo1.txt")
• May give an error, if file doesn’t exist.
• So, check if file exists, then delete it:
import os
if os.path.exists("demo1.txt"):
os.remove("demo1.txt")
else:
print("The file does not exist")
To delete an entire folder, use
the os.rmdir() method:
import os
os.rmdir(“python")
Note: You can only remove empty folders.
17
import os
os.rename (‘demo1.txt’, ‘hello.txt’)
## syntax
rename(current-name, new-name)
The mkdir() method is used to create the directories
in the current working directory.
import os
#creating a new directory with the name new
os.mkdir(“python")
The getcwd() method returns the current working
directory.
import os
os.getcwd()
18. WITH STATEMENT
The with statement in Python is used for resource
management and exception handling. The with
statement simplifies exception handling by
encapsulating common preparation and cleanup
tasks.
In addition, it will automatically close the file.
there is no need to call file.close() when using
with statement.
The with statement itself ensures proper
acquisition and release of resources.
It is when a pair of statements is to be executed
with a block of code in between.
If any exception occurs in the nested block of
code, then with statement automatically closes
the file. It doesn't let the file to corrupt. 18
Syntax:
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
with open("demo2.txt",'r') as f:
content = f.read();
print(content)
Output:
Python is a high-level, object oriented,
interpreted programming language that
supports many domains of applications like AI,
data science, business analytics etc
Python is a cross-platform, open source language
that supports many hardware architectures
like Raspbery Pi
19. 19
# Python code to illustrate split() function
## provides output as list of elements
with open("demo4.txt", "r") as file:
data = file.readlines()
for x in data:
words = x.split()
print (words)
## defining a list
L = [“All is well n", “Life is beautiful n",
“Happiness is free n"]
# Creating a file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write(“These are magic statements n")
file1.writelines(L)
## writing list elements to file
file1.close() # to change file access modes
## to check whether file is written
with open("myfile.txt", "r") as file1:
# Reading form a file
print(file1.read())
Output:
These are magic statements
All is well
Life is beautiful
Happiness is free
Output:
['python', 'is', 'a', 'easy-to-use']
['open', 'source,', 'high-level,', 'object-oriented']
['programming', 'language']
WITH STATEMENT
20. SEARCHING THROUGH A FILE
Many times, we would like to read a file to search for some specific data within it.
Using control statements, we can extract only those lines which meet our criteria.
20
fhand = open('demo1.txt')
for k in fhand:
if k.startswith('hello') :
print(line)
fhand.close()
Output:
hello and welcome to
fhand = open('demo1.txt', 'r')
for line in fhand:
line = line.rstrip()
if line.startswith('hello') :
continue
print(line)
Output:
This class is about File handling in Python
Now the file has more content!
Output:
hello and welcome to python
application programming
fhand = open('demo1.txt', 'r')
for line in fhand:
line = line.rstrip()
if not line.startswith('hello') :
continue
print(line)
Note: We can skip a line/s in a file by using
the continue statement
21. 21
## allowing user to enter the file name
fname = input('Enter the file name: ')
fhand = open(fname)
count = 0
for line in fhand:
if line.startswith('hello'):
count = count + 1
print('There were', count, 'hello lines in', fname)
SEARCHING THROUGH A FILE
Output:
Enter the file name: demo1.txt
There were 1 hello lines in demo1.txt
Output:
open source, high-level, object-oriented
programming language
Output:
open source, high-level, object-oriented
## using in operator to search
fhand = open('demo4.txt')
for line in fhand:
line = line.rstrip()
if 'python' in line:
continue
print(line)
fhand = open('demo4.txt')
for line in fhand:
line = line.rstrip()
if not 'open' in line:
continue
print(line)
22. HANDLING FILE OPEN ERROR WITH
TRY/EXCEPT
• When we try to open a file which doesn’t exist, python throws back an error, as seen earlier
• There is a better way of handling this using try and except blocks.
22
fname=input("Enter a file name:")
try:
fhand=open(fname)
except:
print("File cannot be opened")
exit()
count =0
for line in fhand:
count+=1
print("Line Number ",count, ":", line)
print("Total lines=",count)
fhand.close()
Output1:
Enter a file name:demo3.txt
Line Number 1 : Hello and welcome
Line Number 2 : This is Bangalore
Line Number 3 : This is Paris
Line Number 4 : This is London
Total lines= 4
Output2:
Enter a file name:krishna.txt
File cannot be opened
In this program, the
command to open a file is
kept within try block. If the
specified file cannot be
opened due to any reason,
then an error message is
displayed using the except
block and the program is
terminated. If the file is
opened successfully, then
we will proceed further to
perform required task using
that file.
23. DEBUGGING
23
While performing operations on files, we may need to extract required set of lines or words or
characters. So, we may use string functions with appropriate delimiters that may exist between the
words/lines of a file.
But, usually, the invisible characters like white-space, tabs and new-line characters are confusing and it
is hard to identify them properly. For example,
>>> s='1 2t 3n 4'
>>> print (s)
1 2 3
4
Here, by looking at output, its difficult make out is it displayed wrongly or deliberately done that way.
Python provides a utility function called as repr() to solve this problem. This method takes any object
as an argument and returns a string representation of that object. For example, the print() can be
modified as –
>>> print (repr(s))
'1 2t 3n 4‘