Python笔记(二)文本的创建和读取
短信预约 -IT技能 免费直播动态提醒
学习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')
程序验证:
文本查看器查看:
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")
程序验证:
Let me go on...
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341