手机版
你好,游客 登录 注册
背景:
阅读新闻

两个简短的Python小程序

[日期:2012-12-09] 来源:Linux社区  作者:buaa_shang [字体:大 中 小]

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()把内存中的行写入打开的文件中.

linux
相关资讯       Python教程  Python小程序 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款