前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python笔记(二)文本的创建和读取

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

作者头像
py3study
发布2020-01-09 16:15:38
5380
发布2020-01-09 16:15:38
举报
文章被收录于专栏:python3

学习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...

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档