根据16章的内容作了一些扩展。

 

比如,判断文件如果存在,就在文件后追加,如不存在则创建。

同时借鉴了shell命令中类似 cat <<EOF > test的方法,提示用户输入一个结尾符。

现在有一个小坑,怎么使用python去读取一个文件的行数,原来有os.system("wc -l filename")倒是可以,但是windows下如何操作呢?回头补填。

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sys import argv
from os import path
script, filename = argv
if path.exists(filename):
    print "We're going to erase %r." % filename
    t_module = "a"
else:
    print "We will create %r." % filename
    t_module = "w"
end_EOF = raw_input("please give me a EOF string")
with open(filename,t_module) as fo:
    line_count = 1
    while True:
        line_content = raw_input("please input %d line string:\n" % line_count)
        if line_content == end_EOF:
            break
        else:
            fo.write(line_content)
            fo.write("\n")

  

posted on 2014-11-05 00:20  Kairong  阅读(191)  评论(0编辑  收藏  举报