Lecture
File Reading and Writing
Python allows you to read from and write to text files using the built-in open() function.
This is useful for saving data to a file or loading it back later.
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 better yet, 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)
- The
withstatement ensures the file closes automatically. - The
read()method loads the entire file into a single 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.")
- The
"w"mode creates the file or replaces its content. - Use the
write()method to add text to the file.
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.")
- The
"a"mode preserves existing content and writes new text at the end.
Summary
| Mode | Description |
|---|---|
"r" | Read only mode |
"w" | Write mode (overwrites file) |
"a" | Append mode (adds to end of file) |
"x" | Create mode, error if it exists |
Lessons in this chapter Β· Python Programming Review
- 1. Variables and Data Types
- 2. Expressions and Arithmetic
- 3. String Operations
- 4. Lists in Python
- 5. List Methods and Slicing
- 6. Tuples and Sets
- 7. Dictionaries - Keys and Values
- 8. Dictionary Methods and Nesting
- 9. Conditional Statements (if, elif, else)
- 10. Loops - for and while
- 11. Control Flow & Data Structures Recap
- 12. Multiple-choice quiz
- 13. Loop Controls (break, continue, pass)
- 14. Functions - Defining and Calling
- 15. Function Arguments and Return Values
- 16. Variable Scope and Nested Functions
- 17. Exception Handling with try/except
- 18. File Reading and Writing
- 19. CSV File Parsing
- 20. Using Built-in Modules (math, random, datetime)
- 21. Importing External Modules
- 22. Fill-in-the-blank quiz
Quiz
0 / 1
How do you automatically ensure a file is closed after reading its contents in Python?
To automatically close a file in Python after reading, use the block.
try-except
def
with
loop
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help