File Handling
File Open: open(filename, mode)
- "r" - Read, Default value, error if the file does not exist
- "a" - Append, creates the file if it does not exist
- "w" - Write, creates the file if it does not exist
- "x" - Create specified file, returns an error if the file exists
- "t" - Default value. Text mode
- "b" - Binary mode (e.g. images)
Syntax
f = open("demofile.txt", "rt")
Read
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
Read characters
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
print(f.read(5)) # Return the 5 first characters of the file
Read Lines: readline()
f = open("demofile.txt", "r")
print(f.readline())
# Loop through the file line by line:
for x in f:
print(x)
Close Files # always close file
File Write
Write to an Existing File
- "a": append to the end of the file
- "w": overwrite any existing content
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
Create a New File
f = open("myfile.txt", "x")
f = open("myfile.txt", "w")
Delete File
import os
os.remove("demofile.txt")
Check if file exists
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
import os
os.rmdir("myfolder")
# only remove empty folders