Python File Handling Readfile, write to file, delete files , CRUD Files handling in python
open() is used to handle files
- "r" - Read - Default value. Opens 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 - Creates the specified file, returns an error if the file exists
- "b" - Binary - Binary mode (e.g. images)
- "t" - Text - Default value. Text mode
1.Read Whole File
f = open("demofile.txt", "r") #"D:\\myfiles\welcome.txt"
print(f.read())
2. Read Part of file ie first 5 charters
print(f.read(5))
3. Read Line from file
f = open("demofile.txt", "r")
print(f.readline()) #read first line
print(f.readline()) # read 2nd line
4. Read file line by line
f = open("demofile.txt", "r")
for x in f:
print(x)
5.close file
f.close()
WRITE TO FILES
1. Append to file
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
It will open files and append the new content
2. overwrite to file
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
DELETE FILE
1. It will remove the file
import os
os.remove("demofile.txt")
2. check if file exist then delete it
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
3.Delete the folder
import os
os.rmdir("myfolder")