The Create file (maketextfile.py) script reminds the user to enter a file name that does not yet exist, and then the user enters each line of the file, and then writes all the text to the text file
1 #!/usr/bin/env python 2 3 ' maketextfile.py--creat text file ' 4 5 import os 6 ls = os.linesep 7 8 # get Fil E name 9 while true:10 if Os.path.exists (fname): #不存在返False, there is a return True11 print "ERROR: '%s ' already exists"% fname12 Else:13 break14 #get file content (text) lines16 all = []17 print] \nenter lines ('. ' by itself to quit). \ n "18 19 #loop until user terminates input while true:21 entry = raw_input (' > ') if entry = = '. ' : break24 else:25 all.append (entry) #write lines to file with proper line-ending28 fobj = open (fname, ' W ') fobj.writelines (['%s%s '% (X,ls) for x]) #列表解析, write each row (each element) in the list to a file, two%s is a string and each line terminator is fobj.close32 print ' D one! '
File read and display (readtextfile.py)
1 #!/user/bin/env python 2 3 ' readtextfile.py--read and display text file ' 4 5 # get filename 6 fname = Raw_inpu T (' Enter filename ') 7 print #隔开提示和文本 8 # Attempt to open file for reading 9 try:10 fobj = open (fname, ' R ') one EXCEP T IOError, e:12 print "* * * File Open error:", E13 else:14 # dispaly content to the screen15 for Eachline in FOB J16 Print eachline,17 fobj.close ()
"Python core Programming" notes