To write something to a file or to read the content of a file in Python it is required to open()
and close()
the file properly.
The best practice in Python is to read/write to a file by using the with
statement – the replacement for commonly used try...finally
error-handling statements.
The with
statement ensures that the file is closed when the block inside it is exited.
This note shows the best practice Python examples of how to write to a file or read the file’s content and save it to a variable.
Cool Tip: How to automate login to a website using Selenium in Python! Read More →
Write to a File in Python
To append something to a file, use the code snippet as follows:
with open('file.txt', 'a') as f: f.write("Something\n")
To write something to a file with truncation:
with open('file.txt', 'w') as f: f.write("Something\n")
Read from a File in Python
To read the content of a file, save it to a variable and print:
with open('file.txt', 'r') as f: output = f.read() print(output)