引言:
最近大半年都在學習python編程,在雙十一的時候購買了《Python編程核心》,看到makeTextFile.py和readTextFile.py兩個例子有點錯誤,所以在這里給修正一下!
makeTextFile.py腳本:
#!/usr/bin/env python #_*_coding:utf8_*_ 'makeTextFile.py -- create text file' import os ls = os.linesep #get filename while True: #需要添加的語句,並且需要縮進,后面的四條語句也需要縮進 fname = raw_input("please input file name:\n") if os.path.exists(fname): print "ERROR: '%s' already exists" % fname else: break #get file content (text) Lines all_list = [] """原著上使用了all做list,但是在使用eclipse是發現有assignment to reserved built-in symbol:all的warning,所以就使用all_list""" #all = [] print "\nEnter lines ('.' by itself to quit).\n" #loop until user terminates input while True: entry = raw_input('> ') if entry == '.': break else: all_list.append(entry) #write lines to file with proper line-ending fobj = open(fname,'w') fobj.writelines(['%s%s' % (x,ls) for x in all_list]) fobj.close() print 'DONE!'
readTextFile.py腳本:
#!/usr/bin/env python #_*_coding:utf8_*_ 'readTextFile.py -- read and display text file' #from makeTextFile import fobj #get filename fname = raw_input('Enter filename: ') print #attempt to open file for reading try: fobj = open(fname,'r') except IOError,e: print "*** file open error: ",e else: #display contents to the screen for eachLine in fobj: print eachLine, fobj.close()
