# module purge; module load python/2.7.2 # just run it, no compiling, no linking, no libraries # variable naming convention: since there are different types it is helpful to append the type to the variable, such as S for a string, File for a file testFile = open('readtest.txt') # open() is a built-in function, no import print type(testFile) # f is a file object # has data and methods jS = testFile.readline() # readline() returns the characters in a line, including newline at end print type(jS) print "\n------------------read and print each line of a text file including newline-------------" while len(jS) > 0: # len is a built-in function print jS jS = testFile.readline() testFile.close() print "\n------------------iterate on file, line by line-------------" gFile = open("readtest.txt") for jS in gFile: # python magic: a text file iterates on lines print jS # python magic: trailing comma suppresses printing of newline gFile.seek(0) # rewind the file print "\n------------------python magic string slicing-------------" s = "Now I have a string" print s print s[1:7] print s[0:7] print s[:7] print s[8:len(s)] print s[8:] print s[8:-1] print s[8:-2] print s[0: :2] # 0: means from the beginning :2 means every 2nd character print "\n------------------suppress newline using string slicing-------------" for j in gFile: print j[:-1] # python magic: slice string from implied beginning to character before last character (which is the newline character) gFile.close() print "\n------------------read the file into a list of strings-------------" gFile = open("readtest.txt") sL = gFile.readlines() print type(sL) print sL print "\n------------------string concatenation: magic plus sign-------------" print sL[2] + sL[1] a = sL[2] a = a[:-1] b = sL[1] b = b[:-1] print a + " and " + b + " both on the same line." gFile.close() """ this is a multi-line of text within triple quotes that will be converted to a string. It will be compiled but will not execute anything""" ''' can use single triple apostrophes '''