一个简单的文本编辑器
- # -*- coding: utf-8 -*-
- from sys import argv # 从 sys 模块导入 argv 函数,
- #argv 是 argument variable 参数变量的简写形式一般在命令行调用的时候由系统传递给程序
- # 一般在命令行调用的时候由系统传递给程序
- script, filename = argv # 利用 argv 函数, 把 argv 中的东西解包, 将所有的参数依次赋予左边的变量名
- print "Were going to erase %r." % filename # 打印文件名参数
- print "If you dont want that, hit CTRL-C (^C)." # 提示输入 CTRL+C 就退出程序
- print "If you do want that, hit RETURN."
- print "Here is the original file:"
- txt = open(filename) # 使用 open 函数打开文件, 并把内容存到 txt 变量中
- print txt.read() # 读取 txt 的内容并打印出来, 这一块是为了读取未清除文件内容并写入其他内容之前的内容
- raw_input("?")
- print "Opening the file..."
- target = open(filename, w) # 以写模式打开文件
- print "Truncating the file. Goodbye!"
- target.truncate() # 用 truncate 函数清除文件内容
- print "Now Im going to ask you for three lines."
- #line1 = raw_input("Line 1:") # 写入三行内容, 保存到 line1,line2 和 line3 的变量中
- txt1 = open(filename, w)
- txt1.write (This is a test.\nReally, it is.)
- txt1.close()
- print "Im going to write these to the file."
- target.write(line2) # 使用 write 函数把 line1 变量中
- target.write("\n") # 使用 write 函数写入一个换行符
- target.write(line2) #使用 write 函数把 line2 变量中
- target.write("\n") # 使用 write 函数写入一个换行符
- target.write(line3) #使用 write 函数把 line3 变量中
- target.write("\n") # 使用 write 函数写入一个换行符
- print "And finally, we close it."
- target.close() # 关闭文件
- filename1 = raw_input("input a filename:")
- filename1_open = open(filename1) # 打开文件
- print "Here is the new file content:"
- print filename1_open.read() # 读取新的文件内容
- print "close opened file..."
- filename1_open.close() # 关闭文件
来源: http://www.bubuko.com/infodetail-2503742.html