python中oepen及fileobject初步整理之划水篇
open选项
参考官方文档,很多东西也没有看懂,将自己理解的部分先整理到这里,以后还是要参阅官方文档的。
open (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
1.file
file这里可以是文件的路径(相对路径或绝对路径),也可以是一个文件描述符。若是一个文件描述符,当文件对象关闭时文件描述符也会关闭,除非closefd选项设置为False.
*file* is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless *closefd* is set to `False`.)
2.mode
指定文件打开的方式。分两部分,一部分是权限(rwxa),另外一部分是打开方式(tb);
权限方式有 只读r,只写w(若存在则覆盖),新建x(若存在则抛异常),追加a;
打开方式有:字符串模式t,二进制模式b
默认权限为'r',默认打开方式为‘t'
mode选项中可以给个'+',表示增加读或写的功能;比如'r+',表示以读和text的方式打开文件,但是还可以写。
U?通用的新行模式,(python官方不建议),,,不懂诶
| Character | Meaning |
|---|---|
'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) |
3.buffering
设置buffer的策略,参数为整数。
| buffering | Meaning |
|---|---|
0 |
关闭buffer(binary mode 专用) |
1 |
line buffering(text mode 专用),binary中就是1个字节 |
>1 |
设置buffer大小 |
| -1 | 默认,使用系统缓冲大小(io.DEFAULT_BUFFER_SIZE) |
4.encoding
设置编码方式,text mode 专用。默认使用系统编码方式。linux/unix中为utf-8 ,win中为gbk。
5.errors
text mode 专用。指定遇到decode或者encode错误时的处理方式。默认为None,即跑异常
| errors | Meaning |
|---|---|
'strict' |
to raise aValueError exception if there is an encoding error. The default value of None has the same effect. |
'ignore' |
ignores errors. Note that ignoring encoding errors can lead to data loss. |
'replace' |
causes a replacement marker (such as '?') to be inserted where there is malformed data. |
'surrogateescape' |
will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding. |
t为一个编码有问题的文本文档
模式errors
In [48]: f = open(t)
In [49]: f.read()
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-49-571e9fb02258> in <module>()
----> 1 f.read()
~/.pyenv/versions/3.6.5/lib/python3.6/codecs.py in decode(self, input, final)
319 # decode input (taking the buffer into account)
320 data = self.buffer + input
--> 321 (result, consumed) = self._buffer_decode(data, self.errors, final)
322 # keep undecoded input until the next call
323 self.buffer = data[consumed:]
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 1: invalid start byte
errors = 'surrogateescape'
In [61]: f=open(t, errors='surrogateescape')
In [62]: f.read()
Out[62]: 'a\udc88\udc91.sss.com\nwww.tudou.com\nwww.dtw.com\n'
errors = 'ignore'
In [57]: f = open(t, errors='ignore')
In [58]: f.read()
Out[58]: 'a.sss.com\nwww.tudou.com\nwww.dtw.com\n'
errors = 'replace'
In [54]: f = open(t, errors='replace')
In [55]: f.read()
Out[55]: 'a��.sss.com\nwww.tudou.com\nwww.dtw.com\n'
6.newline
newline controls howuniversal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
- When reading input from the stream, if newline is
None, universal newlines mode is enabled. Lines in the input can end in'\n','\r', or'\r\n', and these are translated into'\n'before being returned to the caller. If it is'', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. - When writing output to the stream, if newline is
None, any'\n'characters written are translated to the system default line separator,os.linesep. If newline is''or'\n', no translation takes place. If newline is any of the other legal values, any'\n'characters written are translated to the given string.
closefd
关闭文件描述符,True表示关闭它。False会在文件关闭后保持这个描述符。fileobj.fileno()查看.
If closefd is
Falseand a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must beTrue(the default) otherwise an error will be raised.
8.opener
A custom opener can be used by passing a callable as *opener*. The underlying file descriptor for the file object is then obtained by calling *opener* with (*file*, *flags*). *opener* must return an open file descriptor (passing [`os.open`](https://docs.python.org/3.6/library/os.html#os.open) as *opener* results in functionality similar to passing `None`).
fileobject的读写方法:
| Method | meaning |
|---|---|
| read() | 一次读取所有文件 |
| readline() | 一次读取一行 |
| readlines() | 一次读取所有文件,每行放到列表中 |
| write() | 参数为str,将str写入文件 |
| writelines() | 接收一个可迭代对象,读取每个元素(str)并写入到文件 不自动写换行符 |
fileobject的其他方法
| Method | meaning |
|---|---|
| seek() | 指定指针位置,0,1,2表示开头,当前,和结尾。二进制模式下可以前移后移,文本摸下不行 |
| close() | 关闭文件 |
| seekable() | 是否可seek |
| readable() | 是否可读取 |
| writable() | 是否可写 |
| closed | 是否关闭 |
python中oepen及fileobject初步整理之划水篇的更多相关文章
- 001 Python中的基本类型初步介绍
这个但是根据书来整理的,显得有些多,也不够完整. 一:介绍 1.为什么使用内置对象 对象类型是语言的一个部分 内置对象构成了每个python程序的核心部分 二:数字 1.**是乘方 2.math数学模 ...
- Python中几种数据结构的整理,列表、字典、元组、集合
列表:shoplist = ['apple', 'mango', 'carrot', 'banana']字典:di = {'a':123,'b':'something'}集合:jihe = {'app ...
- python中argparse模块用法实例详解
python中argparse模块用法实例详解 这篇文章主要介绍了python中argparse模块用法,以实例形式较为详细的分析了argparse模块解析命令行参数的使用技巧,需要的朋友可以参考下 ...
- Python中的exec、eval使用实例
Python中的exec.eval使用实例 这篇文章主要介绍了Python中的exec.eval使用实例,本文以简洁的方式总结了Python中的exec.eval作用,并给出实例,需要的朋友可以参考下 ...
- 数据库MySql在python中的使用
随着需要存储数据的结构不断复杂化,使用数据库来存储数据是一个必须面临的问题.那么应该如何在python中使用数据库?下面就在本篇博客中介绍一下在python中使用mysql. 首先,本博客已经假定阅读 ...
- **Python中的深拷贝和浅拷贝详解
Python中的深拷贝和浅拷贝详解 这篇文章主要介绍了Python中的深拷贝和浅拷贝详解,本文讲解了变量-对象-引用.可变对象-不可变对象.拷贝等内容. 要说清楚Python中的深浅拷贝,需要 ...
- 一些Python中的二维数组的操作方法
一些Python中的二维数组的操作方法 这篇文章主要介绍了一些Python中的二维数组的操作方法,是Python学习当中的基础知识,需要的朋友可以参考下 需要在程序中使用二维数组,网上找到一种这样的用 ...
- 简介Python中用于处理字符串的center()方法
简介Python中用于处理字符串的center()方法 这篇文章主要介绍了简介Python中用于处理字符串的center()方法,是Python入门中的基础知识,需要的朋友可以参考下 center() ...
- 非常易于理解‘类'与'对象’ 间 属性 引用关系,暨《Python 中的引用和类属性的初步理解》读后感
关键字:名称,名称空间,引用,指针,指针类型的指针(即指向指针的指针) 我读完后的理解总结: 1. 我们知道,python中的变量的赋值操作,变量其实就是一个名称name,赋值就是将name引用到一个 ...
随机推荐
- Windows 2016 安装单机版本Oracle ASM 的简单说明
发现这样弄完 启动之后 就挂了 真蛋疼. 改天再研究一下. 1. 需要给磁盘处理一下 建议使用压缩卷的模式进行处理 如图示 需要新建简单卷 注意设置 然后不进行格式化 2. 然后安装oracle的g ...
- [转帖]2018年的新闻: 国内首家!腾讯主导Apache Hadoop新版本发布
国内首家!腾讯主导Apache Hadoop新版本发布 https://blog.csdn.net/weixin_34194317/article/details/88811258 腾讯也挖了很多 ...
- ARM Cortex-M 系列 MCU 错误追踪库 心得
一. 感谢CmBacktrace开源项目,git项目网站:https://github.com/armink/CmBacktrace 二. 移植CmBacktrace 2.1 准备好CmBacktra ...
- codeforces 816B Karen and Coffee (差分思想)
题目链接 816B Karen and Coffee 题目分析 题意:有个人在学泡咖啡,因此看了很多关于泡咖啡温度的书,得到了n种推荐的泡咖啡温度范围[L1,R1] ,此人将有k种做法推荐的温度记为可 ...
- HTML5地图分布动画
在线演示 本地下载
- php过滤微信昵称中的表情
function filterNickname($nickname) { $nickname = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $nickn ...
- yii自定义验证
自定义验证类 class BaseModel extends Model { public function rules() { return [ ['obj', ContentSecurityVal ...
- WPF:元素绑定
到目前为止都在讨论如何链接两个元素的绑定.但在数据驱动的应用程序中,更常见的情况是创建从不可见的对象中提取数据绑定表达式.唯一的要求是希望显示的信息必须存储在公有的属性中.WPF数据绑定基础结构不能获 ...
- vue+webpack项目环境搭建
首先安装node.js 下载地址:https://nodejs.org/en/download/ 看下是否成功安装 node -v 安装webpack,命令行npm install webpack - ...
- elasticsearch设置执行脚本并添加开机启动 (转)
elasticsearch设置执行脚本并添加开机启动 在/etc/init.d目录下新建文件elasticsearch #!/bin/sh #chkconfig: 2345 80 05 #descri ...