Department of Computer Science & Engineering
FILE HANDLING IN PYTHON
SESSION 2023-2024
SUBMITTED BY: SUBMITTED TO:
HIMANSHU SAINI MR. MEGH SINGHAL
2201920100143 ASSISTANT PROFESSOR
CSE 2nd YEAR CSE DEPARTMENT
FILE HANDLING
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.
File Handling Functions
1. open()
2. write()
3. close()
4. delete()
Department of Computer Science & Engineering
MODES OF FILE OPENING
“r” - (Read) Open a file for reading, error if the file does not exist
“a”- (Append) Opens a file for appending, creates the file if it does not
exist
“w” -(Write) Opens a file for writing, creates the file if it does not exist
“x” -(Create) It create a new file, error occurs if file already exists.
Syntax
f = open(filename, mode)
Department of Computer Science & Engineering
FILE OPENING IN READ MODE
Code
print("Himanshu Saini\n2201920100143")
f = open("Himanshu.txt", "r")
print(f.read())
Output
Department of Computer Science & Engineering
FILE OPENING IN WRITE MODE
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
Department of Computer Science & Engineering
FILE OPENING IN APPEND MODE
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
Department of Computer Science & Engineering
FILE CLOSING IN PYTHON
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()
Department of Computer Science & Engineering
FILE DELETION IN PYTHON
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")
Department of Computer Science & Engineering
Thank You
Department of Computer Science & Engineering