File Handling
File Handling
(23EN1202)
Undergraduate Postgraduate
B.Tech_CS.docx
3/19/2024 1.0001 LECTURE 1 7
Absolute pathname
•Ex: C:\students\undergraduate\Btech_CS.docx
•Ex: undergraduate\Btech_CS.docx
Text Files
Binary Files
Each line contains zero or more characters and maximum of 255 characters.
It stores the information in the same format as in the memory i.e. data is
stored according to its data type so no translation occurs.
Binary files are faster and easier for a program to read and write than text
files.
Data in binary files cannot be directly read, it can be read only through
python program for the same
Output:
<_io.BufferedReader name='test.txt'>
Example for Open()
# Opening a file in different directory
f=open("G:/DSU/CTPY/test.txt")
f
# Opens in w mode(writing only)
f=open("test.txt",'w’)
f
output: <_io.TextIOWrapper name='test.txt' mode='w'
encoding='cp1252'>
⮚Proper closing of a file frees up the resources held with the file.
⮚The closing of file is done with a built-in function close().
Syntax:
fileObject.close()
Closing a File
Example 1
# open a file
f = open("test.txt",'wb')
Syntax
fileobject.write(string)
Example
# open the file with w mode
f = open("test_write.txt",'w’)
Output:
hello
python
jupiter
dsu
programming
3/19/2024 1.0001 LECTURE 1 30
lets check if the file is closed: True
Using Open()
⮚When the file is opened using open() function, file will not be
automatically closed.
⮚Ex: f11=open("test1.txt","r")
for lines in f11:
print(lines)
print("lets check if the file is closed:",f11.closed)
Output:
jupiter
moon
sun
3/19/2024 1.0001 LECTURE 1
lets check if the file is closed: False 31
File Position
⮚When we read a line or some data from a file, the pointer
points to the next line or data, and that when we end up
reading whole file, it returns the empty string.
⮚In Python, the tell() method tells us about the current
position of the pointer.
⮚The current position tells us where reading will start from
at present.
File Position
⮚We can also change the position of the pointer with the help
of seek() method.
⮚Syntax: seek(offset[,from])
⮚ Syntax
os.remove(filename)
Example
⮚ # import os
>>>import os
# deleting the file
>>>os.remove(“test1.txt”)
Methods to Manipulate Files
Methods to Manipulate Files
Activity