Writing to a file

Perform the following steps in order to write to a file:

  1. 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')
  1. 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')
  1. 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()
  1. The preceding code snippet is available for download along with this chapter (write_to_file.py).
  2. When the preceding code snippet is executed, the output is shown as follows:
       I am excited to learn Python using Raspberry Pi Zero