[Tutor] Pickling files in Python

Joe Batt joebatt at hotmail.co.uk
Sat Nov 19 14:28:00 CET 2011









Hi all
 I am new to programming and on a very steep curve. I am using Python 3 to learn and I am having trouble understanding exactly what pickling is. I have written a program that asks for a URL and then writes the source code from the URL to a file, then pickles the file I just created. I am not sure why I pickle something as opposed to just saving it as a normal file?
I saved the url source code file as a .txt and also the pickled file as .txt. I am not sure of the filetype I should save a pickled file as.When I look at the files (the saved source file and the pickled file) they look the same. I am viewing them in notepad on the Mac.
Many thanksJoe
####################################################################  Pickle an object- Puzzle 5 #  Joe Batt 18 Nov 2011 - http://www.pythonchallenge.com/pc/def/peak.html###################################################################
import pickleimport urllib
def geturlfile(urlfile):#gets the user URL from main opens it and saves it to var fileurl    from urllib.request import urlopen    fileurl=urlopen(urlfile)#opens the file on computer and writes the var fileurl to it    html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','w')    for line in fileurl.readlines():        linestring=line.decode("utf-8") #ensures written in string not byte        html_file.write(linestring)    html_file.close() #closes the puzzle file#just prints file to check its correct    html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','r')    filecontents=html_file.read()    html_file.close()    print (filecontents)    print (type(filecontents))
#pickles the file filecontents containing the url file    pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','wb')    pickle.dump(filecontents,pickledfile)    pickledfile.close()           return ()
    
# Main programurlfile=input('Please input the URL ')geturlfile(urlfile) 		 	   		   		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111119/0f940eae/attachment-0001.html>


More information about the Tutor mailing list