Python Flashcards
Syntax: open a file for reading [#to write in it]
f = open(“foo.txt”, “r”) # f = open(“bar.txt”, “w”)
Syntax: read a file
data = f.read #where f is the result of: open(“foo.txt”, “r”)
Syntax: write to a file
g.write(“some text\n”) #where g is a result of open(“bar.txt”, “w”)
Syntax: reading a file one line at a time
f = open(“foo.txt”,”r”)
for line in f:
#process line
f.close()
Syntax: reading from the web
import urllib
u = urllib.urlopen("www.google.com") data = u.read()
Syntax: parse an xml doc
from xml.etree.ElementTree import parse
doc = parse(‘rt22.xml’)
Syntax: iterate over an element in a parsed xml doc
for element in doc.findall('element'): #code
Syntax: extract data from a parsed xml doc
d = element.findtext(‘d’)
Syntax: show a page in a browser
import webbrowser
webbrowser.open(‘http://…’)
Syntax: chained comparison
if x < y >= z: #same as: if x < y and y >= z: #but! y only evaluated once, z not if x <y false
Syntax: preferred way to open a file! (to ensure it is closed)
with open('name', 'mode') as f: read_data = f.read()
Syntax: start the development server
python manage.py runserver
Syntax: awesome list comprehension
output = ‘, ‘.join([p.question for p in latest_poll_list])