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 ...

Get Python Programming with Raspberry Pi now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.