File Handling
1.What is File Handling?
File handling allows your Python program to:
Read data from files
Write data to files
Update files
Delete files
Python uses the built-in function open() to work with files.
2.File Opening Modes
Mode Meaning
"r" Read (file must exist)
"w" Write (creates new or overwrites)
"a" Append (adds to end of file)
"x" Create new file (error if file exists)
"r+" Read and write
"w+" Write and read
"a+" Append and read
Syntax of open()
file = open("demo.txt", "r")
Closing a File
file.close()
Reading from File
1.Read full file
f = open("data.txt", "r")
print(f.read())
f.close()
2.Read first 10 characters
print(f.read(10))
3.Read line by line
print(f.readline())
4.Read all lines
lines = f.readlines()
print(lines)
Writing to File
1.Write (overwrite)
f = open("new.txt", "w")
f.write("Hello Python!")
f.close()
2.Append
f = open("new.txt", "a")
f.write("\nNew line added")
f.close()
File Exists or Not
import os
if os.path.exists("test.txt"):
print("File found")
else:
print("File not found")
Deleting a File
import os
os.remove("test.txt")
Top comments (0)