Perform the following steps in order to write to a file:
- The first step in writing to a file is opening a file with the write flag: w. If the file name that was passed as an argument doesn't exist, a new file is created:
file = open('write_file.txt', 'w')
- Once the file is open, the next step is passing the string to be written as argument to the write() function:
file.write('I am excited to learn Python using
Raspberry Pi Zero')
- Let's put the code together where we write a string to a text file, close it, re-open the file and print the contents of the file to the screen:
if __name__ == "__main__":
# open text file to write
file = open('write_file.txt', 'w')
# write a line from the file
file.write('I am excited to learn Python using
Raspberry Pi Zero \n')
file.close()
file = open('write_file.txt', 'r')
data = file.read()
print(data)
file.close()
- The preceding code snippet is available for download along with this chapter (write_to_file.py).
- When the preceding code snippet is executed, the output is shown as follows:
I am excited to learn Python using Raspberry Pi Zero