標籤:字串 adt user img nat line att quit write
建立檔案(makeTextFile.py)指令碼提醒使用者輸入一個尚不存在的檔案名稱,然後由使用者輸入檔案每一行,最後將所有文本寫入文字檔
1 #!/usr/bin/env python 2 3 ‘makeTextFile.py -- creat text file‘ 4 5 import os 6 ls = os.linesep 7 8 # get file name 9 while True:10 if os.path.exists(fname): #不存在返False,存在返True11 print "ERROR: ‘%s‘ already exists" % fname12 else: 13 break14 15 #get file content (text) lines16 all = []17 print "\nEnter lines (‘.‘ by itself to quit).\n"18 19 #loop until user terminates input 20 while True:21 entry = raw_input(‘>‘)22 if entry == ‘.‘:23 break24 else:25 all.append(entry)26 27 #write lines to file with proper line-ending28 fobj = open(fname, ‘w‘)29 fobj.writelines([‘%s%s‘ % (x,ls) for x in all])30 #列表解析,將列表中每行(每個元素)都寫入檔案,兩個%s分別是字串和每行結束符31 fobj.close32 print ‘DONE!‘
檔案讀取和顯示(readTextFile.py)
1 #!/user/bin/env python 2 3 ‘readTextFile.py -- read and display text file‘ 4 5 # get filename 6 fname = raw_input(‘Enter filename‘) 7 print #隔開提示和文本 8 # attempt to open file for reading 9 try:10 fobj = open(fname, ‘r‘)11 except IOError, e:12 print "*** file open error:",e13 else:14 # dispaly content to the screen15 for eachLine in fobj16 print eachLine,17 fobj.close()
《python核心編程》筆記