# Read a file
try:
f = open("demofile.txt")
f.close()
print("Accessed file OK")
except FileNotFoundError:
print("File does not exist")
finally:
print("All done.")
"""
Syntax:
open("filename", "mode")
Default mode values:
r = read
t = text
These are the same
f = open("demofile.txt")
f = open("demofile.txt", "rt")
Open Modes:
r = read
a = append = Open for appending, creates if file does not exist
w = write = Open for writing, creates if file does not exist
x = create = Creates the file for writing, returns error if already exists
Handling modes:
t = text
b = binary
"""
# Open, read, and display a file
f = open("c:\\temp\\demofile.txt", "r")
print(f.read())
f.close()
# Open and read 5 characters
f = open("demofile.txt", "r")
# "This "
print(f.read(5))
f.close()
# Open and read a line
f = open("demofile.txt", "r")
# "This is"
print(f.readline())
f.close()
# Open and read two lines
f = open("demofile.txt", "r")
# "This is"
print(f.readline())
print(f.readline())
f.close()
# Open and loop through each line of the file
f = open("demofile.txt", "r")
for x in f:
print(x)
f.close
# Append to a file
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close
# Open and loop through each line of the file
f = open("demofile2.txt", "r")
for x in f:
print(x)
f.close
# Overwrite a file if it exists
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
# Delete a file
import os
os.remove("demofile2.txt")
# If the file exists, delete it
if os.path.exists("demofile3.txt"):
os.remove("demofile3.txt")
else:
print("The file does not exist")