# # working with files # # copy files "study" and "magnetism" to Python25 folder from string import * # (A) open file and show contents filename = raw_input("Enter file name: ") infile = open(filename,'r') x = infile.read() # read complete file into a variable print print "%s contains the string:\n%s\n\nwhen printed:\n\n%s" % (filename,[x],x) # EXTRA PRINT AND PAUSE pause = raw_input("(pausing... hit enter to continue) ") # close file and reopen infile.close() infile = open(filename,'r') # (B) read a line at a time m = input("\nHow many lines in file? ") for i in range(m): x = infile.readline() print "Line %d is:\n%s" % (i+1,[x]) # EXTRA PRINT AND PAUSE pause = raw_input("\n(pausing... hit enter to continue) ") # close file and reopen infile.close() infile = open(filename,'r') # (B.2) print each line print for i in range(m): x = infile.readline() print x # EXTRA PRINT AND PAUSE pause = raw_input("(pausing... hit enter to continue) ") # close file and reopen infile.close() infile = open(filename,'r') # (B.3) print each line without last character of the line print for i in range(m): x = infile.readline() print x[:-1] # EXTRA PRINT AND PAUSE pause = raw_input("\n(pausing... hit enter to continue) ") # close file and reopen infile.close() infile = open(filename,'r') # (C) loop through file in a couples ways print for line in infile.readlines(): print line[:-1] # EXTRA PRINT AND PAUSE pause = raw_input("\n(pausing... hit enter to continue) ") # close file and reopen infile.close() infile = open(filename,'r') # (C.2) using file variable print for line in infile: print line[:-1] # EXTRA PRINT AND PAUSE pause = raw_input("\n(pausing... hit enter to continue) ") # close file and reopen infile.close() infile = open(filename,'r') # (D) write an upper case version of file outfile = open("OUT"+filename,'w') for line in infile: x = upper(line[:-1])+'\n' outfile.write(x) outfile.close() # close file and reopen output file infile.close() infile = open("OUT"+filename,'r') # print output file print for line in infile: print line[:-1] # EXTRA PRINT AND PAUSE pause = raw_input("\n(pausing... hit enter to continue) ") infile.close()