Read and write a file in Python and show the content round trip.
The open function returns a file object you read from or write to, and the with statement closes it when the block ends.
import os
import tempfile
path = os.path.join(tempfile.gettempdir(), "tutorsbot_demo.txt")
with open(path, "w", encoding="utf-8") as handle:
handle.write("first line\n")
handle.write("second line\n")
with open(path, "r", encoding="utf-8") as handle:
content = handle.read()
print(content)
print(len(content.splitlines()))
os.remove(path)Writing with the w mode creates the file if it does not exist and truncates it if it does. Reading it back with read gives the whole contents as one string, and splitlines confirms there are two lines.
The three reading methods are worth knowing separately. read returns the entire file as a single string, readline returns just the next line, and readlines returns a list of all the lines. Each also has an optional size argument for reading a fixed number of characters or lines, which is how you peek at the beginning of a large file without loading it.
Two habits from the snippet are worth keeping. Always pass encoding explicitly, because the default depends on your operating system's locale and can differ between a developer machine and a server. And always use the with statement, so the file is closed even if an exception happens in the middle of the block.