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.
  1. closefd

    关闭文件描述符,True表示关闭它。False会在文件关闭后保持这个描述符。fileobj.fileno()查看.

    If closefd is False and 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 be True(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初步整理之划水篇的更多相关文章

  1. 001 Python中的基本类型初步介绍

    这个但是根据书来整理的,显得有些多,也不够完整. 一:介绍 1.为什么使用内置对象 对象类型是语言的一个部分 内置对象构成了每个python程序的核心部分 二:数字 1.**是乘方 2.math数学模 ...

  2. Python中几种数据结构的整理,列表、字典、元组、集合

    列表:shoplist = ['apple', 'mango', 'carrot', 'banana']字典:di = {'a':123,'b':'something'}集合:jihe = {'app ...

  3. python中argparse模块用法实例详解

    python中argparse模块用法实例详解 这篇文章主要介绍了python中argparse模块用法,以实例形式较为详细的分析了argparse模块解析命令行参数的使用技巧,需要的朋友可以参考下 ...

  4. Python中的exec、eval使用实例

    Python中的exec.eval使用实例 这篇文章主要介绍了Python中的exec.eval使用实例,本文以简洁的方式总结了Python中的exec.eval作用,并给出实例,需要的朋友可以参考下 ...

  5. 数据库MySql在python中的使用

    随着需要存储数据的结构不断复杂化,使用数据库来存储数据是一个必须面临的问题.那么应该如何在python中使用数据库?下面就在本篇博客中介绍一下在python中使用mysql. 首先,本博客已经假定阅读 ...

  6. **Python中的深拷贝和浅拷贝详解

    Python中的深拷贝和浅拷贝详解   这篇文章主要介绍了Python中的深拷贝和浅拷贝详解,本文讲解了变量-对象-引用.可变对象-不可变对象.拷贝等内容.   要说清楚Python中的深浅拷贝,需要 ...

  7. 一些Python中的二维数组的操作方法

    一些Python中的二维数组的操作方法 这篇文章主要介绍了一些Python中的二维数组的操作方法,是Python学习当中的基础知识,需要的朋友可以参考下 需要在程序中使用二维数组,网上找到一种这样的用 ...

  8. 简介Python中用于处理字符串的center()方法

    简介Python中用于处理字符串的center()方法 这篇文章主要介绍了简介Python中用于处理字符串的center()方法,是Python入门中的基础知识,需要的朋友可以参考下 center() ...

  9. 非常易于理解‘类'与'对象’ 间 属性 引用关系,暨《Python 中的引用和类属性的初步理解》读后感

    关键字:名称,名称空间,引用,指针,指针类型的指针(即指向指针的指针) 我读完后的理解总结: 1. 我们知道,python中的变量的赋值操作,变量其实就是一个名称name,赋值就是将name引用到一个 ...

随机推荐

  1. 利用commons-pool2自定义对象池

    一.为什么使用对象池   恰当地使用对象池化技术,可以有效地减少对象生成和初始化时的消耗,提高系统的运行效率.commons-pool2是Apache下一个开源的公共资源池.我们可以根据它来快速的建立 ...

  2. java this的作用

    this: 区分成员变量和局部变量的重名问题,this.name指的是类中的成员变量,而不是方法内部的

  3. CF 148D Bag of mice 题解

    题面 这是我做的第一道概率DP题: 做完后发现没有后效性的DP是真的水: 在这里说主要是再捋顺一下思路: 设f[i][j]表示有i只白鼠,j只黑鼠是获胜的概率: 显然:f[i][0]=1; 然后分四种 ...

  4. [BZOJ1576] [BZOJ3694] [USACO2009Jan] 安全路径(最短路径+树链剖分)

    [BZOJ1576] [BZOJ3694] [USACO2009Jan] 安全路径(最短路径+树链剖分) 题面 BZOJ1576和BZOJ3694几乎一模一样,只是BZOJ3694直接给出了最短路树 ...

  5. Java switch case 语句

    switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支. 语法 switch(expression){ case value : //语句 break; //可选 ca ...

  6. python-day38(正式学习)

    目录 线程 线程开启的两种方式 1 2 子线程和子进程的创建速度 子线程共享资源 线程的join方法 守护线程 线程其他用法 线程 线程开启的两种方式 1 from threading import ...

  7. Echarts饼图将数据显示在 legend 旁边

    不多废话,笔记如下 var myEcharts = echarts.init(document.getElementById('doughnut')); option = { tooltip: { t ...

  8. 客户端相关知识学习(三)之Android原生与H5交互的实现

    Android原生与H5交互的实现 H5调用原生的方式 方式可能有多种,根据开发经验,接触过两种方式. 方法一:Android向H5注入全局js对象,也就是H5调Android 1.首先对WebVie ...

  9. Charles学习(四)之使用Map local代理本地静态资源以及配置移动端代理在真机上调试iOS和Android客户端

    前言 问题一:我们在App内嵌H5开发的过程中,肯定会遇到一个问题就是我不想在chrome的控制台中调试也不想在模拟器中调试,我想要在真机上调试,那么如何解决这个问题呢? 问题二:我们期待调试时达到的 ...

  10. 109、Secret的使用场景 (Swarm16)

    参考https://www.cnblogs.com/CloudMan6/p/8082429.html   我们可以用secret管理任何敏感数据.这些敏感数据是容器在运行时需要的.同时我们又不想把这些 ...