File Reading and Writing
Python lets you read from and write to text files with the built-in open()
function.
This is useful when you want to save data to a file or load data from one.
1. Opening a File
Use open(filename, mode)
to work with a file.
"r"
= read (default)"w"
= write (overwrites file)"a"
= append (adds to the end)"x"
= create (fails if file already exists)
Always close a file after using it, or use a with
block to handle this automatically.
2. Reading a File
Open a file in "r"
mode to read its contents.
Reading a File
with open("greeting.txt", "r") as file:
content = file.read()
print(content)
with
ensures the file is closed automatically.file.read()
loads the entire file as a string.
3. Writing to a File
Open a file in "w"
mode to create or overwrite it.
Writing to a File
with open("note.txt", "w") as file:
file.write("This is a new line.")
"w"
mode creates the file or replaces its content.- Use
file.write()
to add text.
4. Appending to a File
Open a file in "a"
mode to add new content without removing existing data.
Appending to a File
with open("note.txt", "a") as file:
file.write("\nThis line is added.")
"a"
mode preserves existing content and writes new text at the end.
Summary
Mode | Description |
---|---|
"r" | Read only |
"w" | Write (overwrites file) |
"a" | Append (adds to end of file) |
"x" | Create file, error if it exists |
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.