Read and write a file in Python and show the content round trip.
The open() function gives you back a file object that you read from or write to, and the with statement closes that file for you when the block ends. The example below writes two lines into a file, reads the whole file back, and then prints how many lines it found.
# Write a small file in the current folder.
with open('notes.txt', 'w', encoding='utf-8') as handle:
handle.write('first line\n')
handle.write('second line\n')
# Read the whole file back into one string.
with open('notes.txt', 'r', encoding='utf-8') as handle:
content = handle.read()
print(content)
print('lines:', len(content.splitlines()))
The w mode creates the file when it does not exist and empties it when it does. The r mode reads the file back as one single string, and splitlines() then tells you that the string holds two lines.
There are three reading methods that are worth knowing separately. read() returns the entire file as one string, readline() returns only the next line, and readlines() returns a list with all of the lines in it. Each of them also takes an optional size, so you can read a fixed number of characters or lines. That is how you look at the beginning of a very large file without loading all of it.
Two habits from this snippet are worth keeping. Always pass the encoding explicitly, because the default depends on the settings of the machine you are running on and it can be different on a developer laptop than on a server. And always use the with statement, so that the file is closed even when something goes wrong inside the block.