14 File Handling Basics
14 File Handling Basics
Closing a file:
After completing our operations on the file, it is highly recommended to close
the file. For this we have to use close() function.
Syntax:
fileobject.close()
fileobject.write("string")
Ex:
f=open("test.txt",'w')
f.write("Python")
f.write("Java")
print("Write operation completed")
f.close()
In the above program all lines write in a file as single line. We can use
\n to convert line by line.
Ex:
f=open("test.txt",'w')
f.write("Python \n")
f.write("Java \n")
f.close()
print("Write operation completed")
f.writelines(list of lines): - To write multiple lines at one time.
Ex:
f=open("test.txt",'w')
l=["gangadhar","lokesh","rajesh","lohit"]
f.writelines(l)
f.close()
print("Write operation completed")
Ex:
f=open("test.txt",'r')
print(f.read())
f.close()
readline method by default provide new line at the end of the line. That’s
every time two lines created. To overcome the problem we can use end
attribute in print statement.
Ex:
f=open("test.txt",'r')
line=f.readline()
print(line,end='')
line=f.readline()
print(line, end='')
f.close()
Ex:
f=open("test.txt",'r')
lines=f.readlines()
for line in lines:
print(line)
f.close()
Ex:
f=open("test.txt")
data=f.read(3)
print(data)
print(f.readline())
print(f.read(4))
f.close()
Ex: Write a python program which produces its own source code as its
output
File positions:
tell(): - To return current position of the cursor. File pointer at the starting
position it returns 0.
Ex:
f=open("abc.txt",'r')
pos=f.tell()
print("Current position=",pos)
str=f.read(5)
print(str)
pos=f.tell()
print("Current position=",pos)
str=f.read(5)
print(str)
pos=f.tell()
print("Current position=",pos)
Ex:
f=open("test.txt",'r')
pos=f.tell()
print("Current position=",pos)
f.seek(10,0)
str=f.read(5)
print(str)
pos=f.tell()
print("Current position=",pos)
f.seek(5,0)
str=f.read(5)
print(str)
pos=f.tell()
print("Current position=",pos)
Ex:
data="All Students are normal"
f=open("abc.txt","w")
f.write(data)
with open("abc.txt","r+") as f:
text=f.read()
print(text)
print("Current position=",f.tell())
f.seek(17)
print("The Current position=",f.tell())
f.write("Gems!!!")
f.seek(0)
text=f.read()
print("Data after modification")
print(text)
Ex:
data="All Students are Gems!!!"
f=open("abc.txt","w")
f.write(data)
with open("abc.txt","r+") as f:
f.seek(1000)
f.write("Gangadhar")
print(f.tell())