FILES
• Files are used to store and retrieve data permanently. Python provides built-in functions
to handle file operations such as reading, writing, and appending data.
Opening a File
file = open("filename", "mode")
"filename": Name of the file with its extension (e.g., "data.txt").
"mode": Specifies how the file is opened ("r", "w", "a", "rb", etc.).
COMMON FILE MODES
Mode Meaning
"r" Read (default), file must exist
Write, creates a new file or overwrites
"w"
existing
"a" Append, adds data to the end of the file
"x" Create, fails if the file exists
"b" Binary mode (e.g., "rb", "wb")
"t" Text mode (default, can be omitted)
WRITING TO A FILE
write() – writes string to the file
file = open("example.txt", "w") # Overwrites file
file.write("Hello, Python!")
file.close() lines = ["Line1\n", "Line2\n", "Line3\n"]
file = open("example.txt", "w")
If the file does not exist, it will be created. file.writelines(lines)
If the file exists, it will be overwritten.
file.close()
writelines() – writes list of strings
READING FROM A FILE
read() – reads entire content readline() – reads one line at a time
file = open("example.txt", "r")
content = file.read() file = open("example.txt", "r")
print(content) line1 = file.readline()
file.close() print(line1)
file.close()
READING FROM A FILE
readlines() – returns all lines as a list readline() – reads one line at a time
file = open("example.txt", "r") file = open("example.txt", "r")
lines = file.readlines() line1 = file.readline()
for line in lines: print(line1)
print(line.strip()) file.close()
file.close()
APPENDING TO A FILE
file = open("example.txt", "a")
file.write("\nThis line is appended.")
file.close()
RENAMING A FILE
You must import the os module:
import os
os.rename("example.txt", "newfile.txt")
DELETING A FILE
import os
os.remove("newfile.txt")
CHECKING FILE EXISTENCE BEFORE DELETING
(OPTIONAL)
import os
if os.path.exists("newfile.txt"):
os.remove("newfile.txt")
else:
print("File does not exist.")
Function Purpose
open() Open/create a file
read() Read entire content
readline() Read one line
write() Write a string
writelines() Write a list of strings
close() Close the file
os.rename() Rename the file
os.remove() Delete the file