学习Python已有数日,这是今天的战利品:
1.创建文本(createtext.py)
程序如下:
#create text file
import os
ls = os.linesep
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
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")
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)
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')
fobj = open(fname, 'w')
fobj.writelines(['%s%s' %(x,ls) for x in all])
fobj.close()
print ('Done')
程序验证:
![](https://i-blog.csdnimg.cn/blog_migrate/dca72c99366341fdfe5776634a6ae849.jpeg)
文本查看器查看:
![](https://i-blog.csdnimg.cn/blog_migrate/bdd76a3955c9ba66ff84055966ff9cd9.jpeg)
2.读取文本文件(readtext.py)
程序如下:
#read and dislay text file
print("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")
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")
程序验证:
![](https://i-blog.csdnimg.cn/blog_migrate/31d5d31d46eff800b43af67cd45b2e36.jpeg)
Let me go on...
转载于:https://blog.51cto.com/neo1989/278898