Python File Handling Functions
Python File Handling Functions
File handling in python allows the user to read, write, and other operation on
file. Python treats files directly as text or binary. Each line of code includes a
sequence of characters and they form a text file.
Syntax
f = open(filename, mode)
print("Himanshu Saini\n2201920100143")
f = open("Himanshu.txt", "r")
print(f.read())
Output
Code
print("Himanshu Saini\n2201920100143")
f= open("Himanshu.txt","w")
f.write("Now the file has more content!")
f.close()
p= open("Himanshu.txt","r")
print(p.read())
Output
Code
print("Himanshu Saini\n2201920100143")
f = open("Himanshu.txt", "a")
f.write("Now the file has more content!")
f.close()
p = open("Himanshu.txt", "r")
print(p.read())
Output
close() function closes the file. It is used at the time when the file is
no longer needed or if it is to be opened in a different file mode.
Syntax
file_object.close()
Code
file1 = open("Himanshu.txt", "r")
file1.close()
To delete a file, we will have to import the OS module and run its
os.remove() function
Syntax
os.remove(“filename”)
Code
import os
if os.path.exists("Himanshu.txt"):
os.remove("Himanshu.txt")
else:
print("The file does not exist")