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