Skip to content

Commit

Permalink
补充读取文件的方式
Browse files Browse the repository at this point in the history
  • Loading branch information
iswbm committed Apr 3, 2021
1 parent 3664e3b commit d67af1c
Showing 2 changed files with 60 additions and 2 deletions.
30 changes: 29 additions & 1 deletion source/c03/c03_11.md
Original file line number Diff line number Diff line change
@@ -24,12 +24,40 @@ with fileinput.input(files=('data.txt',)) as file:

## 第三种:使用 filecache

使用内置库 filecache
使用内置库 filecache,你可以用它来指定读取具体某一行,或者某几行,不指定就读取全部行。

```python
import linecache

content = linecache.getlines('werobot.toml')
```

## 第四种:使用 codecs

使用 `codecs.open` 来读取

```python
import codecs
file=codecs.open("README.md", 'r')
file.read()
```

如果你还在使用 Python2,那么它可以帮你处理掉 Python 2 下写文件时一些编码错误,一般的建议是:

- 在 Python 3 下写文件,直接使用 open
- 在 Python 2 下写文件,推荐使用 codecs.open,特别是有中文的情况下
- 如果希望代码同时兼容Python2和Python3,那么也推荐用codecs.open

## 第五种:使用 io

使用最底层的 io 模块

```python
import io
file=io.open("README.md")
file.read()
```



![](http://image.iswbm.com/20200607174235.png)
32 changes: 31 additions & 1 deletion source/c03/c03_11.rst
Original file line number Diff line number Diff line change
@@ -28,14 +28,44 @@
第三种:使用 filecache
----------------------

使用内置库 filecache
使用内置库
filecache,你可以用它来指定读取具体某一行,或者某几行,不指定就读取全部行。

.. code:: python
import linecache
content = linecache.getlines('werobot.toml')
第四种:使用 codecs
-------------------

使用 ``codecs.open`` 来读取

.. code:: python
import codecs
file=codecs.open("README.md", 'r')
file.read()
如果你还在使用 Python2,那么它可以帮你处理掉 Python 2
下写文件时一些编码错误,一般的建议是:

- 在 Python 3 下写文件,直接使用 open
- 在 Python 2 下写文件,推荐使用 codecs.open,特别是有中文的情况下
- 如果希望代码同时兼容Python2和Python3,那么也推荐用codecs.open

第五种:使用 io
---------------

使用最底层的 io 模块

.. code:: python
import io
file=io.open("README.md")
file.read()
|image1|

.. |image0| image:: http://image.iswbm.com/20200804124133.png

0 comments on commit d67af1c

Please sign in to comment.