Skip to content

Instantly share code, notes, and snippets.

@dustinsgoodman
Created May 7, 2013 03:22
Show Gist options
  • Save dustinsgoodman/5530045 to your computer and use it in GitHub Desktop.
Save dustinsgoodman/5530045 to your computer and use it in GitHub Desktop.
An example of using file input and output.
#example file writing procedure
f = open("/home/sharocko/Documents/Codecademy/output.txt", "w") #open the file for writing
f.write("Hello World\n") #write a string to the file
f.close() #close the file when we're done
#example file reading procedure
f = open("/home/sharocko/Documents/Codecademy/output.txt", "r") #open the file for reading
print f.read() #read data from the file
f.close() #close the file when we're done
#example file appending procedure
f = open("/home/sharocko/Documents/Codecademy/output.txt", "a+") #open the file for appending and reading
f.write("See I append the file.\n") #write data to the file
print f.read() #print the contents from the file, note that it's only from the end of the file so we get nothing
f.close() #close the file when we're done
#uncomment the following to see the real contents of the file
#f = open("/home/sharocko/Documents/Codecademy/output.txt", "w")
#f.write("Hello World\n")
#f.close()
f = open("/home/sharocko/Documents/Codecademy/output.txt", "w+") #open the file for reading and writing
print f.read() #read the content from the file, notice how there isn't anything
f.write("New text for the file.\n") #write some data to the file
print f.read() #read the content, note that we don't see anything because our pointer is at the end of the file
f.close() #close the file when we're done
#add a open with read permission to see the content of the above file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment