|
| 1 | +# Day 13: File I/O - Reading and Writing to Files |
| 2 | + |
| 3 | +# File I/O (Input/Output) allows your program to interact with files |
| 4 | +# on your computer's storage. |
| 5 | + |
| 6 | +# Best practice: use the 'with open(...)' statement. It automatically |
| 7 | +# closes the file for you, even if errors occur. |
| 8 | + |
| 9 | +# 1. Writing to a file using 'w' mode (write) |
| 10 | +# The 'w' mode creates the file if it does not exist, or overwrites it if it does. |
| 11 | +print("Writing to file...") |
| 12 | +with open("notes.txt", "w") as file: |
| 13 | + file.write("Hello, Python learner!\n") |
| 14 | + file.write("This is a new line of text.\n") |
| 15 | + file.write("This information will be saved permanently.") |
| 16 | +print("Done writing to notes.txt.") |
| 17 | + |
| 18 | +# 2. Reading from a file using 'r' mode (read) |
| 19 | +# The 'r' mode opens the file for reading. |
| 20 | +print("\nReading from file...") |
| 21 | +with open("notes.txt", "r") as file: |
| 22 | + file_content = file.read() # Reads the entire content as a single string |
| 23 | + print("File content:") |
| 24 | + print(file_content) |
| 25 | + |
| 26 | +# 3. Appending to a file using 'a' mode (append) |
| 27 | +# The 'a' mode adds new content to the end of the file without overwriting it. |
| 28 | +print("\nAppending to file...") |
| 29 | +with open("notes.txt", "a") as file: |
| 30 | + file.write("\nThis is an appended line of text.") |
| 31 | +print("Done appending.") |
| 32 | + |
| 33 | +# Let's read the file again to see the appended content |
| 34 | +print("\nReading file after appending...") |
| 35 | +with open("notes.txt", "r") as file: |
| 36 | + final_content = file.read() |
| 37 | + print("Final file content:") |
| 38 | + print(final_content) |
0 commit comments