《python核心编程》笔记——文件的创建、读取和显示
创建文件(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,存在返True 11 print "ERROR: '%s' already exists" % fname 12 else: 13 break 14 15 #get file content (text) lines 16 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 break 24 else: 25 all.append(entry) 26 27 #write lines to file with proper line-ending 28 fobj = open(fname, 'w') 29 fobj.writelines(['%s%s' % (x,ls) for x in all]) 30 #列表解析,将列表中每行(每个元素)都写入文件,两个%s分别是字符串和每行结束符 31 fobj.close 32 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:",e 13 else: 14 # dispaly content to the screen 15 for eachLine in fobj 16 print eachLine, 17 fobj.close()