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 sample.txt file using write()
[ ]: f = open("sample.txt", "w")
x = f.write("Hello World")
print(x)
f.close()
11
1
1.4 Reading the content of sample.txt file using read()
[ ]: f = open("sample.txt", "r")
x = f.read()
print(x)
print(type(x))
f.close()
Hello World
Keshav Mahavidyalaya
Univeristy of Delhi
India
<class 'str'>
1.5 Reading the content of sample.txt file using readline()
[ ]: f = open("sample.txt", "r")
while True:
x = f.readline()
if x:
print(x)
else:
break
print(type(x))
f.close()
Hello World
Keshav Mahavidyalaya
Univeristy of Delhi
India
<class 'str'>
1.6 Reading the content of sample.txt file using readlines()
[ ]: f = open("sample.txt", "r")
filecontent = f.readlines()
for i in filecontent:
print(i)
print(type(filecontent))
2
f.close()
Hello World
Keshav Mahavidyalaya
Univeristy of Delhi
India
<class 'list'>
1.7 Writing a list in sample.txt file using writelines()
[ ]: f = open("sample2.txt", "w")
x = ["Keshav", " Mahavidyalaya"]
y = f.writelines(x)
f.close()
1.8 append in sample2.txt
[ ]: f = open("sample2.txt", "a")
f.write("\nDelhi University")
f.close()
1.9 seek and tell
Keshav Mahavidyalaya Delhi University
[ ]: f = open("sample2.txt", "r")
print(f.read(4))
print(f.tell())
print(f.seek(0))
print(f.read(4))
f.close()
Kesh
4
0
Kesh
[ ]: f = open("sample.txt", "r")
x = f.readline(5)
print(x)
f.close()
Hello