Main.FileWrite History

Hide minor edits - Show changes to markup

March 05, 2013, at 02:08 PM MST by 129.82.44.223 -
Added lines 1-37:

(:source lang=python:)

""" Writing data to a file """

  1. note that the command

file_handle = open('numbers.txt')

  1. can also be written as:

file_handle = open('numbers.txt', 'r')

  1. the additional argument tells python that we want to open the file for
  2. the purpose of reading from it (the mode in which to open the file).
  3. 'r' is the default mode, so can be omitted.
  4. if you want to write to a file simply open it in write mode ('w')
  5. (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')

  1. note that we needed to explicitly put in a new-line character.

file_handle.write('now it has two lines\n')

  1. and close the file when done:

file_handle.close()

  1. 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()

  1. The write method of a file takes a string as its argument.
  2. If you want to write a floating point number or integer you need to
  3. 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()

(:sourceend:)