黑松山资源网 Design By www.paidiu.com
1这是一个创建一个文件,并在控制台写入行到新建的文件中.
#!/usr/bin/env python 'makeTextFile.py -- create text file' import os ls = os.linesep #get filename while True: fname = raw_input('Enter filename:') if os.path.exists(fname): print "ERROR: '%s' already exists" % fname else: break #get file content (text) lines all = [] print "\nEnter lines('.' by itself to quit).\n" #loop until user terminates input while True: entry = raw_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!' os.linesep表示行结尾标志, 用本地变量名ls代替它节省了时间,并减少了消耗系统资源. 用 raw_input()读入文件名 用列表all[]来保存每一行文本(它们暂时在内存中). 最后创建文件后,用writelines()把内存中的行写入打开的文件中.
#!/usr/bin/env python 'readTextFile.py -- read and display text file' #get filename fname = raw_input('Enter filename: ') print #attempt to open file for reading try: fobj = open(fname, 'r') except IOError, e: print "*** file open error:", e else: #display contents to the screen for eachLine in fobj: print eachLine, fobj.close()
(1)注意:由于我们没有移除代表每行结束的行结束符,我们不得不抵制 print 语句自动生成的行结束符 --通过在print 语句的最后加一个逗号可以达到这一目的
print 后没有逗号是这种效果:
(2) try-except-else是一个新出現的语句,其中except子句是我们处理错误的地方.
注:两个程序在执行前,需要给文件增加可执行权限.
$chmod a+x filename
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- 徐璨宾《井底的蚯蚓》[320K/MP3][78.77MB]
- 碧蓝航线国庆金秋版本重磅上线 新玩法3D宿舍系统闪亮登场
- 自在西游自在服即将在10月1日开启 入驻即享豪礼满满
- 炉石传说最强术士卡组是哪个 术士最强天梯卡组推荐一览
- 炉石传说最强萨尔卡组是哪个 萨尔最强天梯卡组推荐一览
- 炉石传说最强潜行者卡组是哪个 潜行者最强天梯卡组推荐一览
- 银霞.1983-《爱迷惑我·我住小楼中》台湾复刻版[WAV+CUE]
- [雨果唱片]粤曲名家-《再折长亭柳》[WAV+CUE]
- 刘德华1998-你是我的女人[香港第二版][WAV]
- 压迫感谁最强?外媒评选恐怖游戏最佳女反派
- 还没正式发售:《寂静岭2:重制版》Steam玩家峰值近9000人
- 别搞政确了!超95%国外玩家反对强制包容性
- 《暗喻幻想:ReFantazio》试玩:ATLUS的自我挑战?
- 《憧憬成为魔法少女》第二季 反转魔法少女题材再掀热潮
- 海信AI电视E7N正式发布,引领AI画质新标杆