Python 3 — Reading & Writing Files
Variables only persist while your program is running. The moment the script ends, the memory is cleared. To save data permanently, you must write it to files. Python provides simple built-in file operators for reading and writing files.
To open a file, use the open() function. The first parameter is the file path, and the second is the mode: "w" (write) or "a" (append). We use the with block to guarantee the file is closed automatically:
# Writing to a new file (overwrites old file if it exists)
with open("test_file.txt", "w") as file:
file.write("Hello from Python File writing!\n")
file.write("This data is saved to the disk.\n")
print("File written successfully!")
To read a file, open it in read mode ("r") and read the contents using '.read()' (reads entire file) or a loop to process it line-by-line:
# Reading the file we wrote above
with open("test_file.txt", "r") as file:
content = file.read()
print(content)
If you open a file with "w" mode, Python will delete the existing file content. To preserve existing data and add text to the bottom, open the file in append ("a") mode:
with open("test_file.txt", "a") as file:
file.write("Adding this new line without wiping old data!\n")
Historically, files were opened and closed manually using f = open(); f.close(). If your code crashed before the close line, the file remained locked. Using the with statement handles closing for you automatically, even during crashes.
Write a script that creates a file called 'notes.txt' and writes three checklist items in it. Then, reopen the file in read mode and print each line out to the console terminal.