#coding: utf-8
# 本例旨在只做一个简单的文本编辑器,运行这个程序需要输入一个你想创建的文件名,无所谓存在与否,比如:python ex16.py test.txt
from sys import argv # 常规操作调用
script, filename = argv # 注意这个script,在所有的参数里都第一个申明它,以后在使用它时也要作这样的申明
print "We're going to erase %r." % filename # 我们将要消除...文件
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?") # 这里有点意思,这个是一个"暂停符",如果回车在继续进行,^C就退出
print "Open the file..."
target = open(filename, 'w') # 这里指用写入的方式读取此文件,open函数详解不妨参阅http://www.runoob.com/python/python-func-open.html
print "Truncating the file. Goodbye!"
target.truncate() # 此时target是我们要处理的目标文件的内容
print "Now I'm going to ask you for three lines."
# 这里预先分配变量,后面输入
line1 = raw_input("line 1: ") # 输入第一行的内容
line2 = raw_input("line 2: ") # 输入第二行的内容
line3 = raw_input("line 3: ") # 输入第三行的内容
print "I'm going to write these to the file."
target.write(line1) # write函数也是没有返回值,用法为<目标文件>.write(<提示信息>)
target.write("\n") # 打印换行符
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close() # close函数,关闭前面的target
# 为了温习上一节的内容,我们再次将它打开
x = filename
txt = open(filename)
print txt.read()
ex16.py 读写文件
最新推荐文章于 2023-07-20 12:54:59 发布