""" Writing data to a file """ # note that the command file_handle = open('numbers.txt') # can also be written as: file_handle = open('numbers.txt', 'r') # the additional argument tells python that we want to open the file for # the purpose of reading from it (the mode in which to open the file). # 'r' is the default mode, so can be omitted. # if you want to write to a file simply open it in write mode ('w') # (it doesn't need to exist beforehand): file_handle = open('my_new_file.txt', 'w') file_handle.write('this file now has one line\n') # note that we needed to explicitly put in a new-line character. file_handle.write('now it has two lines\n') # and close the file when done: file_handle.close() # If you would like to add stuff to a file, open it in append mode ('a'): file_handle = open('my_new_file.txt', 'a') file_handle.write('we just added another line\n') file_handle.close() # The write method of a file takes a string as its argument. # If you want to write a floating point number or integer you need to # convert it to a string first using str() or the formatting operator (%): file_handle = open('my_new_file.txt', 'a') file_handle.write(str(1.1) + '\n') file_handle.write('%2.1f %2.1f' % (150.3333, 20.289) + '\n') file_handle.close()