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. java中start()、yield、setDeamon()

    本节主要说明以下三个问题 start()的启动顺序不代表线程的启动顺序 yeild的作用 守护线程 1.start()与线程启动顺序 package foreverly.cn.chapter1; pu ...

  2. n=C(2,n)+k(构造)( Print a 1337-string)Educational Codeforces Round 70 (Rated for Div. 2)

    题目链接:https://codeforc.es/contest/1202/problem/D 题意: 给你一个数 n ( <=1e9 ),让你构造137713713.....(只含有1,3,7 ...

  3. 简单的shell练习

    1.判断/etc/inittab文件是否大于100行,如果大于,则显示”/etc/inittab is a big file.”否者显示”/etc/inittab is a small file.”# ...

  4. Python-RabbitMQ-RPC(非阻塞版)

    服务器端:rpc_server.py import pika,time connection = pika.BlockingConnection(pika.ConnectionParameters(h ...

  5. javaScript基础知识总汇

    javaScript是什么: 1.JavaScript 运行在客户端(浏览器)的编程语言 2.用来给HTML网页增加动态功能 3.用来给HTML网页增加动态功能. 4.Netscape在最初将其脚本语 ...

  6. 2018最新版 手机号、验证码正则表达式 jq + 小程序

    HTML: <!-- 表单 --> <input class="weui-input" id="tel" type="tel&quo ...

  7. Qt表格导出图片

    概述:qt中把某个控件导出保存为图片导出并不复杂,网上也有一堆方法.但是对于tableview中数据很多的情况下势必会出现滚动条,用传统的截屏抓图势会有滚动条,图片数据展示不全.在这我使用了一种折中方 ...

  8. LintCode 68---Binary Tree Postorder Traversal

    /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, ri ...

  9. html5_禁止复制网站内容

    ```//若是你不想别人复制你的网站内容,可以把这段js代码加到你网页上,即可屏蔽鼠标右键菜单.复制粘贴.选中等 有时候的需求是网站中有些内容不希望别人复制,那么就需要用代码控制.方法有多种:第一种: ...

  10. javascript--获取一个页面各个标签的数量

    获取一个页面各个标签的数量 document.getElementsByTagName('*')--获取所有的标签. var obj = document.getElementsByTagName(' ...