IO流文件读写
2016-04-26 13:44
274 查看
#P1 打开文件、读文件、关闭文件的典型方法 try: f=open('D:/test.txt','r') print(f.read()) finally: if f: f.close() #P2 推荐的简洁写法,不必显示的关闭文件描述符 #open返回的对象在python中称作file-like 对象,可以是字节流、网络流、自定义流等 with open('D:/test.txt','r') as f: #按行读取 for line in f.readlines(): print(line.strip()) #P3 直接读取二级制的图片、视频文件 # with open('D:/banner.jpg','rb') as f2: # for line in f2.readlines(): # print(line.strip()) #P4 可以指定编码读取相应的数据,还可以忽略非法编码 with open('D:/test.txt','r',encoding='gbk',errors='ignore') as f3: for line in f3.readlines(): print(line.strip()) #P5 写文件的流程和读文件是一样的 代开文件、写入内容、关闭文件 # 'r' open for reading (default) # 'w' open for writing, truncating the file first # 'x' open for exclusive creation, failing if the file already exists # 'a' open for writing, appending to the end of the file if it exists # 'b' binary mode # 't' text mode (default) # '+' open a disk file for updating (reading and writing) # 'U' universal newlines mode (deprecated) with open('D:/test12.txt','a+') as f4: for line in f4.readlines(): print(line.strip()) f4.write('a new line2!')
相关文章推荐
- nginx安装
- 如何“有效地一对一会谈”
- 学习: .NET XML实例演练,遍历XML文档和构造XML文档
- HNOI2016 游记
- 导入hadoop Maven项目时,eclipse pom.xml提示Missing artifact jdk.tools:jdk.tools:jar:1.6 的解决方案
- java学习笔记
- 003-storm设计思想和处理过程
- Item 06: 若不想使用编译器自动生成的函数,就该明确拒绝
- flume 使用 spool source的时候字符集出错
- Newtonsoft.Json
- Linux下Keepalived 安装与配置
- SQLZOO(More JOIN operations)Writeup
- 我U盘中的efi manager
- iOS程序启动原理
- CentOS7.1上安装Apache + SVN
- ios导航栏透明
- 信长之野望
- APNs改动 (转)
- 使用JS遇到的问题点
- JavaScript 函数讲解