Sie sind auf Seite 1von 2

Python Cheat Sheet #Files f = open("file path", 'mode: r, w, a, r+') f.close() f.read() f.readline() f.tell() - where are we f.

seek(offset amount, 'from where: 0,1,2') for line in f: # interpreted to do readline for each line with open('a file pathname', 'r') as f: stuff to do program continues # this assures that the file will be closed after the body of the with group has executed ## a simple way to unpickle an entire file: file = open(filename,'rb') size = file.see(0,2) contents = [] file.seek(0) while file.tell() < size: contents.append(pickle.load(file)) import cpickle to get the optimized version written in C! ## function structure in stand-alone modules must have a main() must have a way to call main() so it runs def main(argv): ... if __name__ == "__main__": sys.exit(main(sys.argv[1:])) # __main__ is the context of the c aller, which can be either the python shell (idle) or the cmd shell a method call changes the object so it is like treating the object as gl obal. an assignment creates or changes a local variable #Directories -- modules (os, os.path) current directory: os.getcwd() change to absolute directory: os.chdir("absolute path") change to relative directory: os.chdir(".\\sub directory path\\") listing of current directory: os.listdir('.') is g a file: test = os.path.isfile(g) is g a directory: os.path.isdir(path) Return True if path is an existing directory. This follows symbolic links, s o both islink() and isdir() can be true for the same path. is g a symbolic link: os.path.islink(path) ##importing directories as packages: use platform indendent dir syntax: import dir1.dir2.mod #dir1 must be in the python search path, mod is actually mod.py each dir must contain a file __init__.py which can be empty or can run initi alization code from . import foobar #will import a module foobar from the current package (of the package code containing import) import search order varies in 2.6/(2.7?) and 3.0: the problem is making sur

e that you can import std library modules morale: try to avoid re-using the names for std. library modules for your o wn code. #Making a copy instead of a reference: cc = alist[:] cc = list(alist) cd = adictionary.copy() import copy x = copy.deepcopy(y) #copies recursively all nested objects in y #Input and output Be sure to use raw_input instead of input in Python 2.7 #formatting string output print '%s ... %s ... %s' % (obj1, obj2, obj3) #print list must be a tu ple print '{0} ... {1} ... {2}'.format(obj1, obj2, obj3) #there are a bunch --too many--ways to code the string selector #Math beware integer math. In 2.x: 3 / 5 => 0 NOT .6 3 / float(5) => .6 In 3.x: 3 / 5 => .6 and 3 // 5 => 0 (for backwards compatibility. it's called "floor division" because it rounds down. IT DOES NOT TRUNCATE. BEWARE! #Strings instant parsing to characters: turn any string into a list with the list functi on as: list(stringvar) translate method to remove noise characters: str = str.translate(None,',.:;') removes all white space and returns the words as a list: str = str.split() Sort all of the words with the sort method: words.sort() (sorts the list in plac e) #Functions ##Some handy functions zip map #Dictionaries a fast way to build a dictionary. myd = dict(zip(keys, values)) #Database access Try pymysql and mysqldb and oursql #Running at shell level sys.argv returns a list of cmdline arguments: 0: module name 1: etc...

Das könnte Ihnen auch gefallen