Working with files lets your programs store and retrieve data. Python makes basic file operations easy with the open() function.
Opening a file
Use open() with the file name and mode.
Common modes:
-
"r": read (default) -
"w": write (overwrites if file exists) -
"a": append (adds to end) -
"r+": read and write
file = open("example.txt", "r")
Always close the file when done:
file.close()
Better: use with (automatically closes):
with open("example.txt", "r") as file:
# work with file
# file is closed here automatically
Reading from a file
Read entire content:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Read line by line:
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip removes newline
Read all lines into a list:
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
Writing to a file
Write (overwrites):
with open("output.txt", "w") as file:
file.write("Hello, file!\n")
file.write("Second line.")
Append:
with open("output.txt", "a") as file:
file.write("\nNew appended line.")
Write multiple lines:
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("list.txt", "w") as file:
file.writelines(lines)
Simple examples
Save user input to a file:
name = input("Enter your name: ")
with open("names.txt", "a") as file:
file.write(name + "\n")
Read and display a file:
try:
with open("data.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found.")
Important notes
- Use
withto avoid forgetting to close files. - Specify encoding if needed:
open("file.txt", "r", encoding="utf-8") - Handle
FileNotFoundErrorwhen reading non-existent files. - Writing in
"w"mode deletes existing content.
Quick summary
- Open files with
open()and usewithfor safety. - Read with
.read(),.readlines(), or loop. - Write with
.write()or.writelines(). - Use
"r"for reading,"w"for writing,"a"for appending. - Always handle possible errors.
Practice reading from and writing to simple text files. File operations are essential for persistent data in Python programs.
Top comments (0)