Python With Open
来源:互联网 发布:c语言基础代码大全 编辑:程序博客网 时间:2024/06/11 01:17
在学习python的时候,书中写着
txt = open(filename)
txt.close()
这种读取方式,通过和同学的交流得知with open 方式可以节省文件的close
通过查询资料。使用with open 调用代码更加整洁 也节省了try catch的框框
例子如下
1.读文件
with open(filename) as f:
f.read(); # 可赋值 可输出
2.写文件
with open(filename, 'w') as f:
f.write("something to write") #可传递参数
3.多个文件
只需将 as 后面的 f 换成其他对象
ps.读写方式类型
读写模式的类型有:rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)w 以写方式打开,a 以追加模式打开,从末尾开始r+ 以读写模式打开w+ 以读写模式打开 a+ 以读写模式打开 rb 以二进制读模式打开wb 以二进制写模式打开 ab 以二进制追加模式打开 rb+ 以二进制读写模式打开 wb+ 以二进制读写模式打开 ab+ 以二进制读写模式打开 ps.带字符编码读取open(filename,'r',encoding="gbk")ps.Copy例子from sys import argvfrom os.path import exists#from file_name1 to file_name2script, file_name1, file_name2 = argvprint "Copy from {0} to {1}".format(file_name1,file_name2)#open filewith open(file_name1) as f: indata = f.read()#get lengthprint "The input file is %d bytes long" % len(indata)print "Dose the output file exist %r" % exists(file_name2)print "Ready, hit RETURN to continue, CTRL-C to abort"raw_input()with open(file_name2,'w') as out: output = out.write(indata)print "its ok"
阅读全文
0 0
- python with open
- Python With Open
- Python with open语句
- open source ids with python
- python之with open as
- python的with open as f
- eoprocessing with Python using Open Source GIS
- python文本读写,with open as
- python-4-之with和open对比
- 用with open完成python读写
- Python中关于with open file as 的用法
- python中with open as结构最好不要嵌套使用
- [问答]Python 打开多个文件怎么使用 "with open"
- Python文件操作,with open as追加文本内容实例
- python open
- python open()
- python open
- python open()
- easyui时间显示到月
- python 的类(上)
- Tensorflow学习之旅(九)——自编码AutoEncoder
- Redis性能压测工具 redis-benchmark
- java maven工程读取resource下文件的方法
- Python With Open
- drools与maven项目整合实例(1)-HelloWorld
- 详细教你如何部署ICE服务(一)
- MySQL数据库数据增删改查语言和使用例子
- 算法概论习题8.14
- python 小工具总结
- Servlet学习
- 钉钉自定义机器人
- VM356:1 Uncaught SyntaxError: Unexpected token i in JSON at position 1