•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 401,449 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,889 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Views: 52315 | Replies: 144
![]() |
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
The Python module pickle allows you to save objects to file as a byte stream that contains the object information. When you load the file back the object is intact. Here is a little code example ...
The same procedure applies to other objects like variables, tuples, sets, dictionaries and so on.
python Syntax (Toggle Plain Text)
import pickle myList1 = [1, 2, 03, 04, 3.14, "Monte"] print "Original list:" print myList1 # save the list object to file file = open("list1.dat", "w") pickle.dump(myList1, file) file.close() # load the file back into a list file = open("list1.dat", "r") myList2 = pickle.load(file) file.close() # show that the list is still intact print "List after pickle.dump() and pickle.load():" print myList2
Last edited by vegaseat : Mar 1st, 2007 at 2:32 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
The Python module calendar is another interesting collection of functions (methods). If you ever need to show all 12 monthly calendars for the year, use this code ...
If you just want June 2005 use ...
Just for fun, ask a C++ programmer to do this in two lines of code. Now you know why Python is considered a high level language.
Here is a somewhat more complete program, asking the user for the year ...
Since I have Dev-C++ on my computer I tricked it into using Python and do the calendar thing.
python Syntax (Toggle Plain Text)
# print out a given year's monthly calendars import calendar calendar.prcal(2005)
python Syntax (Toggle Plain Text)
import calendar calendar.prmonth(2005, 6) """ result --> June 2005 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 """
Here is a somewhat more complete program, asking the user for the year ...
python Syntax (Toggle Plain Text)
# allowing for user input import calendar print "Show a given year's monthly calendars ..." year = int(raw_input("Enter the year (eg. 2005): ")) calendar.prcal(year) raw_input("Press Enter to go on ...") # wait
cpp Syntax (Toggle Plain Text)
// needs the Python-2.4.1.DevPak installed into Dev-C++, download from: // http://prdownloads.sourceforge.net/devpaks/Python-2.4.1.DevPak?download // create project with File > New > Project... > Scripting > Python #include <iostream> #include <string> // run the Python interpreter eg. Python24.dll // this macro saves on typing! #define PY PyRun_SimpleString(input.c_str()) using namespace std; // include the Python library header extern "C" { #include <python2.4/Python.h> } int main() { // initialize Python Py_Initialize(); // optional - display Python version information cout << "Python " << Py_GetVersion() << endl << endl << endl; string input; // this module is in Python24\lib as calendar.py // could include it in the working folder if problem input = "import calendar"; PY; // print out the year's monthly calendar input = "calendar.prcal(2005)"; PY; // finish up and close Python Py_Finalize(); cin.get(); // console wait return 0; }
Last edited by vegaseat : Mar 1st, 2007 at 2:36 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
Since we are on the subject of modules that come with Python, there is the operating system module called simply os. Here is one thing you can use it for ...
There are lots of things you can do with this module. I guess you just have to type help('os') in the interactive window (the one with the >>> prompt) .
You Mac folks will have to change the folder/directory name and the extension.
python Syntax (Toggle Plain Text)
# list all the configuration (.ini) files in C:\Windows import os fileList = [] # start with an empty list for filename in os.listdir("C:/Windows"): if filename.endswith(".ini"): fileList.append(filename) # now show the list for filename in fileList: print filename
You Mac folks will have to change the folder/directory name and the extension.
Last edited by vegaseat : Mar 1st, 2007 at 2:37 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
We have used the replace() function before. This time we use it in a for loop to create new words. The example also gives us a look at the if conditional statement ...
A variation of the above to show off the if/else statement ...
These little code samples are fun to experiment with.
A note for the C programmers, Python treats characters as strings. This makes life a lot simpler!
python Syntax (Toggle Plain Text)
# make your own words, when Q comes up we want to use Qu str1 = 'Aark' print "Replace A in %s with other letters:" % str1 # go from B to Z for n in range(66, 91): ch = chr(n) if ch == 'Q': # special case Q, use Qu ch = ch + 'u' print str1.replace('A', ch)
python Syntax (Toggle Plain Text)
# make your own words, here we have to avoid one # word to get past the guardians of the nation's morals str1 = 'Auck' print "Replace A in %s with other letters:" % str1 # go from B to Z for n in range(66, 91): ch = chr(n) if ch == 'Q': # special case Q, use Qu ch = ch + 'u' if ch == 'F': # skip the F word continue else: print str1.replace('A', ch)
A note for the C programmers, Python treats characters as strings. This makes life a lot simpler!
Last edited by vegaseat : Mar 1st, 2007 at 2:38 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
Instead of reading a file, you can read the HTML code of a web site. Of course, you have to be connected to the internet to do this ...
Notice that we have added the try/except exception handling to this code.
If you are the curious type and want to know beforehand whether you are connected to the internet, this code might tell you ...
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
python Syntax (Toggle Plain Text)
# if you are on the internet you can access the HTML code of a given web site # using the urlopen() method/function from the module urllib2 import urllib2 urlStr = 'http://www.python.org/' try: fileHandle = urllib2.urlopen(urlStr) str1 = fileHandle.read() fileHandle.close() print '-'*50 print 'HTML code of URL =', urlStr print '-'*50 except IOError: print 'Cannot open URL %s for reading' % urlStr str1 = 'error!' print str1
If you are the curious type and want to know beforehand whether you are connected to the internet, this code might tell you ...
python Syntax (Toggle Plain Text)
# are we connected to the internet? import os def isSSL(): """ return true if there is a SSL (https) connection """ if (os.environ.get('SSL_PROTOCOL', '') != ''): return true else: return false if isSSL: print "We have a SSL connection" else: print "No SSL connection"
Last edited by vegaseat : Mar 1st, 2007 at 3:11 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
Do you want to impress your friends? Of course you do! Try this Python code example using the datetime module ...
The datetime module is smart enough to catch erroneous dates like date(1983, 12, 32) or date(1983, 2, 29).
Notice the variation of the import statement. Here we are just importing the date method from the datetime module. This saves you from having to code:
now = datetime.date.today()
Might be good for long code where you would have to write this twenty times.
Here is another practical code ...
Calculations like this can lead to a lot of headscratching, Python does it for you without a scratch ...
Impressed? I am!
python Syntax (Toggle Plain Text)
# how many days old is this person? from datetime import date # a typical birthday year, month, day # or change it to your own birthday... birthday = date(1983, 12, 31) now = date.today() print '-'*30 # 30 dashes print "Today's date is", now.strftime("%d%b%Y") print "Your birthday was on", birthday.strftime("%d%b%Y") # calculate your age age = now - birthday print "You are", age.days, "days old"
Notice the variation of the import statement. Here we are just importing the date method from the datetime module. This saves you from having to code:
now = datetime.date.today()
Might be good for long code where you would have to write this twenty times.
Here is another practical code ...
python Syntax (Toggle Plain Text)
# calculate days till xmas from datetime import date now = date.today() # you may need to change the year down the road xmas = date(2005, 12, 25) tillXmas = xmas - now print '-'*30 # 30 dashes print "There are", tillXmas.days, "shopping days till xmas!"
python Syntax (Toggle Plain Text)
# add days to a given date from datetime import date, timedelta now = date.today() delta = timedelta(days=77) addDays = now + delta print '-'*30 # 30 dashes print "Today's date is :", now.strftime("%d%b%Y") print "77 days from today:", addDays.strftime("%d%b%Y")
Last edited by vegaseat : Mar 1st, 2007 at 2:40 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
This little fun with numbers program shows how range() and the for loop work together. A little trick I learned in fourth grade applied to Python.
python Syntax (Toggle Plain Text)
# call it "all the same" num1 = 12345679 # the 8 is left out! # k goes from 9 to <82 in steps of 9 for k in range(9, 82, 9): print num1 * k
Last edited by vegaseat : Mar 1st, 2007 at 2:41 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
I took this from a recent thread, to show you how you can use a temporary print statement to figure out what is going on ...
Just a little note, when you save this code, don't save it as random.py. Python will confuse this in the import statement! It will look for the module random.py in the working directory first, before it goes the \Lib directory where the proper module is located.
python Syntax (Toggle Plain Text)
# create a jumbled word/string import random # create a sequence, here a tuple, of words to choose from WORDS = ("python", "jumble", "easy", "difficult", "answer", "babysitter") # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word # create a jumbled version of the word # start with an empty string to be built up in the while loop jumble = "" # word is reduced in size by one character each time through the loop # when it is empty it will be equal to None(False) and the loop stops while word: print word,' ', jumble # for test only position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] print jumble # now you can ask to guess the word ...
Last edited by vegaseat : Mar 1st, 2007 at 2:41 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
Strings are immutable, which means you cannot directly change an existing string, bummer! The following code would give you an error ...
Where there is a will, there is a way around this obstacle ...
Along the last thought, lets have some word fun ...
The last code example could be the start of a "guess the word" game.
python Syntax (Toggle Plain Text)
str1 = 'Hello World!' str1[0] = "J" # gives TypeError: object does not support item assignment
python Syntax (Toggle Plain Text)
str1 = 'Hello World!' # these statements give the intended result, since they create a new string # slicing and concatination str2 = 'J' + str1[1:] # using replace() str3 = str1.replace('H', 'J') # or change the string to a list of characters, do the operation, and join the # changed list back to a string charList = list(str1) charList[0] = 'J' str4 = "".join(charList) print str1 print str2 print str3 print str4
python Syntax (Toggle Plain Text)
# just a little word fun ... import random str1 = "Mississippi" charList = list(str1) random.shuffle(charList) str2 = "".join(charList) print "\nString '%s' after random shuffle = '%s'" % (str1, str2)
Last edited by vegaseat : Mar 1st, 2007 at 2:42 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,425
Reputation:
Rep Power: 9
Solved Threads: 173
Another recent thread was the impetus for this hint.
As you run the Python interpreter on a Python text code file (.py), the file is internally compiled to a .pyc byte code file that speeds up the interpretation process. Most of the time this is transparent to you, as the byte code file for speed sake is created in memory only.
If a Python text code .py file is imported by another Python file, a corresponding .pyc is created on disk to speed up the reuse of that particular file. Using .pyc files speeds things up saving the compilation step.
There is an additional benefit, the compiled files are not readable with a text editor. You can distribute your .pyc file instead of the .py file, this way you can hide your source code a little from folks who like to fiddle with source code.
Let's say you have a file called MyPyFile.py and want to create the compiled file MyPyFile.pyc for higher speed and/or the prevention of unauthorized changes. Write a little one line program like this:
Save it as CompileMyPyFile.py in the same folder as MyPyFile.py and run it. There now should be a MyPyFile.pyc file in that folder. Python.exe runs the source file or the compiled file.
Here is another way to create the compiled file ...
Note: Changed code tags, looks like we lost the php tags!
As you run the Python interpreter on a Python text code file (.py), the file is internally compiled to a .pyc byte code file that speeds up the interpretation process. Most of the time this is transparent to you, as the byte code file for speed sake is created in memory only.
If a Python text code .py file is imported by another Python file, a corresponding .pyc is created on disk to speed up the reuse of that particular file. Using .pyc files speeds things up saving the compilation step.
There is an additional benefit, the compiled files are not readable with a text editor. You can distribute your .pyc file instead of the .py file, this way you can hide your source code a little from folks who like to fiddle with source code.
Let's say you have a file called MyPyFile.py and want to create the compiled file MyPyFile.pyc for higher speed and/or the prevention of unauthorized changes. Write a little one line program like this:
python Syntax (Toggle Plain Text)
import MyPyFile # converts MyPyFile.py to MyPyFile.pyc
Here is another way to create the compiled file ...
python Syntax (Toggle Plain Text)
# create a byte code compiled python file import py_compile py_compile.compile("MyPyFile.py") # creates MyPyFile.pyc
Note: Changed code tags, looks like we lost the php tags!
Last edited by vegaseat : May 15th, 2007 at 5:44 pm.
May 'the Google' be with you!
![]() |
•
•
•
•
•
•
•
•
DaniWeb Python Marketplace
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: Wizards Warlocks & Window.Refresh()
- Next Thread: Pygame Cursor



Linear Mode