《Python 核心编程》笔记(1) : 3.6 第一个Python 程序

Welcome to the Python World!

断断续续读了《Python核心编程》,现在终于读到了3.6节,无奈手里这个mobi版本的代码图片有些问题,索性记下来,方便回顾。

#!/user/bin/env python

'makeTextFile.py -- creat text file'

import os
ls = os.linesep

#get filename
while True:
    fname=raw_input('input name:')
    if os.path.exists(fname):
        print "ERROR: '%s' already exsits" % fname
    else:
        break

#get file content lines
all=[]
print"\nEnter lines('.'by itself to quit).\n"

#loop until user terminates input
while True:
    entry = raw_input('> ')
    if entry == '.':
        break
    else:
        all.append(entry)

#write lines to file with proper line-ending
fobj = open(fname,'w')
fobj.writelines(['%s%s' % (x,ls)for x in all])
fobj.close()
print 'done!'

后来 linuxsand 又给出了改进的代码,于是变成

# makeTextFile.py -- creat text file
 
import os
 
# get filename
while True:
    fname = raw_input('input name:')
    if os.path.exists(fname):
        print "ERROR: '%s' already exsits" % fname
    else:
        break
 
# get file content lines
lines = [] # all=[], `all` is a built-in function, do not use it
print "\nEnter lines('.'by itself to quit).\n"
 
# loop until user terminates input
while True:
    entry = raw_input('> ')
    if entry == '.':
        break
    else:
        lines.append(entry)
 
# write lines to file with proper line-ending
# using `with` context manager
with open(fname, 'w') as fobj:
    # fobj.writelines(['%s%s' % (x, os.linesep)for x in all])
    fobj.write(os.linesep.join(lines))
 
print 'done!'

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.