FileHandling
February 19, 2023
1 File handling
• files are used for storing data permanently
• basic file operations
• read, write, update, delete
1.1 Access modes
• r : read, default mode to open a file
• w : write, creates a new file if file doesn’t exist, override existing data
• a : append, append text to existing file without overwritting: the handle is positioned at the
end of the file, creates a new file if file doesn’t exist
1.2 Functions
• open : The open() function takes two parameters; filename, and mode and returns handle
• close : Closes the file
• read : Returns the file content, Returns string data type, read(n) n: specifying number of
bytes to read
• readline : Returns one line from the file, Returns string data type, readline(n) n: specifying
number of bytes to read
• readlines : Returns a list of lines from the file, Returns List data type
• write : Writes the specified string to the file, Returns number of bytes written
• writelines : Writes a list of strings to the file, Returns None
• tell : Returns the current file position
• seek : Change the file position
1.3 Writing a string in [Link] file using write()
[ ]: f = open("[Link]", "w")
x = [Link]("Hello World")
print(x)
[Link]()
11
1
1.4 Reading the content of [Link] file using read()
[ ]: f = open("[Link]", "r")
x = [Link]()
print(x)
print(type(x))
[Link]()
Hello World
Keshav Mahavidyalaya
Univeristy of Delhi
India
<class 'str'>
1.5 Reading the content of [Link] file using readline()
[ ]: f = open("[Link]", "r")
while True:
x = [Link]()
if x:
print(x)
else:
break
print(type(x))
[Link]()
Hello World
Keshav Mahavidyalaya
Univeristy of Delhi
India
<class 'str'>
1.6 Reading the content of [Link] file using readlines()
[ ]: f = open("[Link]", "r")
filecontent = [Link]()
for i in filecontent:
print(i)
print(type(filecontent))
2
[Link]()
Hello World
Keshav Mahavidyalaya
Univeristy of Delhi
India
<class 'list'>
1.7 Writing a list in [Link] file using writelines()
[ ]: f = open("[Link]", "w")
x = ["Keshav", " Mahavidyalaya"]
y = [Link](x)
[Link]()
1.8 append in [Link]
[ ]: f = open("[Link]", "a")
[Link]("\nDelhi University")
[Link]()
1.9 seek and tell
Keshav Mahavidyalaya Delhi University
[ ]: f = open("[Link]", "r")
print([Link](4))
print([Link]())
print([Link](0))
print([Link](4))
[Link]()
Kesh
4
0
Kesh
[ ]: f = open("[Link]", "r")
x = [Link](5)
print(x)
[Link]()
Hello