Python学习16:读写文件
2018-02-22 23:32
375 查看
一个简单的文本编辑器
# -*- coding: utf-8 -*- from sys import argv # 从sys模块导入argv函数, #「argv」是「argument variable」参数变量的简写形式。一般在命令行调用的时候由系统传递给程序。 # 一般在命令行调用的时候由系统传递给程序。 script, filename = argv # 利用argv函数,把 argv 中的东西解包,将所有的参数依次赋予左边的变量名 print "We're going to erase %r." % filename # 打印文件名参数 print "If you don't want that, hit CTRL-C (^C)." # 提示输入CTRL+C就退出程序 print "If you do want that, hit RETURN." print print "Here is the original file: " print 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 I'm going to ask you for three lines." print #line1 = raw_input("Line 1: ") # 写入三行内容,保存到line1,line2和line3的变量中 txt1 = open(filename, 'w') txt1.write ('This is a test.\nReally, it is.') txt1.close() print print "I'm going to write these to the file." print 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 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 print filename1_open.read() # 读取新的文件内容 print "close opened file..." filename1_open.close() # 关闭文件
相关文章推荐
- Learn Python The Hard Way学习(16) - 读写文件
- Learn Python The Hard Way学习(16) - 读写文件
- 笨方法学习Python-习题16: 读写文件
- python学习之路三(文件读写)
- 使用os.popen/commands.getoutput查询指定端口号的服务 分类: python 小练习 open()文件读写 python基础学习 2013-09-17 17:49 798人阅读 评论(0) 收藏
- python学习之路三(文件读写)
- python学习:读写文件和字典排序
- Python学习(16)File(文件)方法
- 廖雪峰python学习笔记10&&11:容错处理与文件读写
- 【python学习笔记】pthon3.x中的文件读写操作
- python学习——文件读写
- python读写UCS-2 big/little endian(utf-16-be/utf-16-le)格式的文件
- 【python学习02】- open读写文件
- python基础教程学习笔记---(6)文件读写
- python学习-读写文件
- python学习笔记 IO 文件读写
- 学习 Python 文件的读写
- Python学习之文件读写
- python读写unicode文件之utf-16
- python文件读写实例学习笔记