The file type is built into Python so there is no need to do any imports

11.1 Open/Create a file for writing

The method open("filename", "options") takes two arguments.

options usage
w write
a append
r read
+ create if it does not exist

This will open the file in Python not in a text editor.

def main():
 
  # Open a file for writing and create it if it doesn't exist
  f = open("textfile.txt","w+")
 
if __name__ == "__main__":
  main()

11.2 Open the file for appending

a+ opens the files for appending, or creates it if it doesn't exit

def main():
 
  # Open the file for appending text to the end
  f = open("textfile.txt","a+")
 
if __name__ == "__main__":
  main()

11.3 Append text and close

.write("string") method (which you call on the file you are appending,) takes in the text to append. In this case since its in a for loop and the iterator i is available to us the .write() method can print the control code %d which we have defined as % (i+1)

def main():
 
    # Open the file for appending text to the end
    f = open("textfile.txt","a+")
 
    # write some lines of data to the file
    for i in range(10):
      f.write("This is line %d\r\n" % (i+1))
 
    # close the file when done
    f.close()
 
if __name__ == "__main__":
  main()

N.B. if the textfile is already open in a text editor and you don't see the writing or appending you expect, close and re-open the file.

11.4 Open file and read contents

Call the .read()method on the file

 def main():
 
  # Open the file back up and read the contents
  f = open("textfile.txt","r")
  if f.mode == 'r': # check to make sure that the file was opened
    # use the read() function to read the entire file
    contents = f.read()
    print contents
 
    # close the file when done
    f.close()
 
if __name__ == "__main__":
  main()

11.5 Open file and read lines to list

Call the .readlines() method on the file

def main():
 
  # Open the file back up and read the contents
  f = open("textfile.txt","r")
  if f.mode == 'r': # check to make sure that the file was opened
 
    fl = f.readlines() # readlines reads the individual lines into a list
    for x in fl:
      print x
 
if __name__ == "__main__":
  main()