#!/usr/bin/env python # -*- coding:utf-8 -*-
#书上这个例子跑不了,所以自己改了一下。 \'python核心编程例子3.1:makeTextFile.py -- create text file\' import os import sys ls = os.linesep #获取当前平台使用的行终止符。Windows下返回\'/r/n\',Linux使用\'/n\'。 while True: #按照书的逻辑,此处应该定义个fname,然后循环判断,但是书里没写。 fname = raw_input(\'input file name:\') #创建一个文件名 if os.path.exists(fname): #os.path.exits 判断(目录或文件)是否存在 print "ERROR: \'%s\' already exists" % fname else: break
all = [] #创建all列表 print "\nEnter lines (\'.\' by itself to quit).\n" while True: entry = raw_input(\'>\') if entry == \'.\': break else: all.append(entry) fobj = open(fname, \'w\') fobj.writelines([\'%s%s\' % (x, ls) for x in all]) #循环将列表写入,x 是 all列表里的元素, ls行终止符 fobj.close() print \'DONE!\'