Python笔记(二)文本的创建和读取

2023-01-31 02:01:58 创建 文本 读取
学习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...

相关文章