学习Python已有数日,这是今天的战利品:
 
1.创建文本(createtext.py)
程序如下:
#create text file
 
import os
ls = os.linesep
print("******create file******")
 
#get filename
while True:
    fname = input("enter your file name:")
    if os.path.exists(fname):
        print("error: '%s' already exists"%fname)
    else:
        break
 
#get file content lines
all = []
print("\nEnter lines ('.'by itself to quit).\n")
 
#loop until user terminates input
while True:
    entry = 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')
 
 
 
程序验证:
 
文本查看器查看:
 
 
 
2.读取文本文件(readtext.py)
程序如下:
#read and dislay text file
print("read and dislay text file")

fname = input("Enter filename:")
print        #display a empty line
#attempt to open file for reading
try:
    fobj = open(fname, 'r')
except IOError:
    print("file open error:")
else:
    #display contents
    print('_ '*10,)
    for eachLine in fobj:
        print(eachLine,end = '') #end参数,默认为'\n'
    fobj.close()
print('_ '*10)
print("Done")
 
程序验证:
 
 
 
Let me go on...