SlideShare a Scribd company logo
PYTHON APPLICATION PROGRAMMING -
18EC646
MODULE 2
FILES
Prof. Krishnananda L
Department of ECE
Govt SKSJTI
Bengaluru
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
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
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)
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
• >>>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 corruptedand may not be in an opening state
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
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)
>>>txt="hello n world"
>>> txt
'hello n world'
>>> print (txt)
hello
world
>>> len (txt)
13
>>> txt1=("XnY")
>>> print ("XnY")
X
Y
>>> len(txt1)
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
### 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 between30 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
MODIFYING FILE POINTER POSITIONS
Python provides the tell() method which is used to print
the byte numberat 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
""“ 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-oriente
Read Line:programminglanguage
Read Line:a easy-to-use
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
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:
creatingdemo3.txtfile in writemode
Outputof the file after reading:
Hello and welcome
This is Bangalore
This is Paris
This is London
Outputof Readline functionis
Hello and welcome
14
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
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
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()
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
acquisitionand 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 programminglanguage that
supportsmany domains of applications likeAI,
data science,business analyticsetc
Python is a cross-platform,open source language
that supportsmany hardware architectures
like Raspbery Pi
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
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 byusing
the continuestatement
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
Therewere1 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)
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:
Entera 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:
Entera 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.
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‘

More Related Content

What's hot

File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
nitamhaske
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
Mahendra Yadav
 
File handling(some slides only)
File handling(some slides only)File handling(some slides only)
File handling(some slides only)
Kamlesh Nishad
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
File handling
File handlingFile handling
File handling
Nilesh Dalvi
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
thirumalaikumar3
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Santosh Verma
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
Hitesh Kumar
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
indra Kishor
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
File handling in c
File handling in c File handling in c
File handling in c
Vikash Dhal
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
Python file handling
Python file handlingPython file handling
Python file handling
Prof. Dr. K. Adisesha
 
Data file handling
Data file handlingData file handling
Data file handlingTAlha MAlik
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 

What's hot (20)

File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
File handling(some slides only)
File handling(some slides only)File handling(some slides only)
File handling(some slides only)
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling
File handlingFile handling
File handling
 
File in C language
File in C languageFile in C language
File in C language
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
File handling in c
File handling in c File handling in c
File handling in c
 
File in c
File in cFile in c
File in c
 
Python file handling
Python file handlingPython file handling
Python file handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 

Similar to Python-files

FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
ssuser00ad4e
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
RonitVaskar2
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai saleFile Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
RohitKurdiya1
 
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptxPOWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
samkinggraphics19
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
22261A1201ABDULMUQTA
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
Vishal Dutt
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
ARYAN552812
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
botin17097
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
Mehul Desai
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 

Similar to Python-files (20)

Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai saleFile Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
 
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptxPOWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 

More from Krishna Nanda

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
Krishna Nanda
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
Krishna Nanda
 
Python lists
Python listsPython lists
Python lists
Krishna Nanda
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
Krishna Nanda
 
Python- strings
Python- stringsPython- strings
Python- strings
Krishna Nanda
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layer
Krishna Nanda
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
Krishna Nanda
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
Krishna Nanda
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
Krishna Nanda
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
Krishna Nanda
 
Lk module3
Lk module3Lk module3
Lk module3
Krishna Nanda
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
Krishna Nanda
 
Lk module4 file
Lk module4 fileLk module4 file
Lk module4 file
Krishna Nanda
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
Krishna Nanda
 

More from Krishna Nanda (16)

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 
Python lists
Python listsPython lists
Python lists
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Python- strings
Python- stringsPython- strings
Python- strings
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layer
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
 
Lk module3
Lk module3Lk module3
Lk module3
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Lk module4 file
Lk module4 fileLk module4 file
Lk module4 file
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 

Recently uploaded

在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 

Recently uploaded (20)

在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 

Python-files

  • 1. PYTHON APPLICATION PROGRAMMING - 18EC646 MODULE 2 FILES Prof. Krishnananda L Department of ECE Govt SKSJTI Bengaluru
  • 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 corruptedand 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) >>>txt="hello n world" >>> txt 'hello n world' >>> print (txt) hello world >>> len (txt) 13 >>> txt1=("XnY") >>> print ("XnY") X Y >>> len(txt1)
  • 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 between30 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 numberat 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-oriente Read Line:programminglanguage 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: creatingdemo3.txtfile in writemode Outputof the file after reading: Hello and welcome This is Bangalore This is Paris This is London Outputof Readline functionis 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 acquisitionand 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 programminglanguage that supportsmany domains of applications likeAI, data science,business analyticsetc Python is a cross-platform,open source language that supportsmany 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 byusing the continuestatement
  • 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 Therewere1 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: Entera 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: Entera 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‘