Skip to main content

Writing Files

To write data into a file, open it in 'w' mode:

with open("output.txt", "w") as file:
file.write("Hello, this file is created by Python!\n")
file.write("Writing code is awesome.")

Note: If output.txt already exists, this command clears all its old content and replaces it with the new text.


14.4 Appending Files

To add new lines to the end of a file without deleting the old content, use the 'a' (append) mode:

with open("output.txt", "a") as file:
file.write("\nAdding this new line at the end using Append mode.")

14.5 Reading a File Line-by-Line

For large files, it is better to read them line-by-line using a for loop to save memory:

with open("lines.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes extra blank lines/spaces

:::tip Real-World Use Case File handling is essential for reading server log files, importing CSV reports, or saving simple user preferences! :::