Skip to content

Commit a0d8fa5

Browse files
committed
add file-directory
1 parent be3854d commit a0d8fa5

1 file changed

Lines changed: 220 additions & 0 deletions

File tree

‎File-Directory/text_file_io.md‎

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
# 读写文本文件
2+
3+
读写文件是最常见的 IO 操作。通常,我们使用 `input` 从控制台读取输入,使用 `print` 将内容输出到控制台。实际上,我们也经常从文件读取输入,将内容写到文件。
4+
5+
# 读文件
6+
7+
在 Python 中,读文件主要分为三个步骤:
8+
9+
- 打开文件
10+
- 读取内容
11+
- 关闭文件
12+
13+
一般使用形式如下:
14+
15+
```python
16+
try:
17+
f = open('/path/to/file', 'r') # 打开文件
18+
data = f.read() # 读取文件内容
19+
finally:
20+
if f:
21+
f.close() # 确保文件被关闭
22+
```
23+
24+
注意到,我们在代码中加了 `try...finally`,这是因为,如果打开和读取文件时出现错误,文件就没有被关闭。为了确保在任何情况下,文件都能被关闭,我们加了 `try...finally`。
25+
26+
上面的代码中,'r' 模式表示读模式,`open` 函数的常用模式主要有:
27+
28+
| ‘r' | 读模式 |
29+
| :-: | :-: |
30+
| ‘w' | 写模式 |
31+
| ‘a' | 追加模式 |
32+
| ‘b' | 二进制模式(可添加到其他模式中使用) |
33+
| ‘+' | 读/写模式(可添加到其他模式中使用) |
34+
35+
上面的读文件做法很繁琐,我们可以使用 Python 的 `with` 语句来帮我们自动调用 `close` 方法:
36+
37+
```python
38+
with open('/path/to/file', 'r') as f:
39+
data = f.read()
40+
```
41+
42+
可以看到,这种方式很简洁,而且还能在出现异常的情况下自动关闭文件。
43+
44+
通常而言,读取文件有以下几种方式:
45+
46+
- 一次性读取所有内容,使用 `read()` 或 `readlines()`;
47+
- 按字节读取,使用 `read(size)`;
48+
- 按行读取,使用 `readline()`;
49+
50+
## 读取所有内容
51+
52+
读取所有内容可以使用 `read()` 或 `readlines()`。我们在上面已经介绍过 `read()` 了,现在,让我们看看 `readlines()`。
53+
54+
`readlines()` 方法会把文件读入一个字符串列表,在列表中每个字符串就是一行。
55+
56+
假设有一个文件 data.txt,它的文件内容如下(数字之间的间隔符是'\t'):
57+
58+
```python
59+
10 1 9 9
60+
6 3 2 8
61+
20 10 3 23
62+
1 4 1 10
63+
10 8 6 3
64+
10 2 1 6
65+
```
66+
67+
我们使用 `readlines()` 将文件读入一个字符串列表:
68+
69+
```python
70+
with open('data.txt', 'r') as f:
71+
lines = f.readlines()
72+
line_num = len(lines)
73+
print lines
74+
print line_num
75+
```
76+
77+
执行结果:
78+
79+
```
80+
['10\t1\t9\t9\n', '6\t3\t2\t8\n', '20\t10\t3\t23\n', '1\t4\t1\t10\n', '10\t8\t6\t3\n', '10\t2\t1\t6']
81+
6
82+
```
83+
84+
可以看到,列表中的每个元素都是一个字符串,刚好对应文件中的每一行。
85+
86+
## 按字节读取
87+
88+
如果文件较小,一次性读取所有内容确实比较方便。但是,如果文件很大,比如有 100G,那就不能一次性读取所有内容了。这时,我们构造一个固定长度的缓冲区,来不断读取文件内容。
89+
90+
看看例子:
91+
92+
```python
93+
with open('path/to/file', 'r') as f:
94+
while True:
95+
piece = f.read(1024) # 每次读取 1024 个字节(即 1 KB)的内容
96+
if not piece:
97+
break
98+
print piece
99+
```
100+
101+
在上面,我们使用 `f.read(1024)` 来每次读取 1024 个字节(1KB) 的文件内容,将其存到 piece,再对 piece 进行处理。
102+
103+
事实上,我们还可以结合 yield 来使用:
104+
105+
```python
106+
def read_in_chunks(file_object, chunk_size=1024):
107+
"""Lazy function (generator) to read a file piece by piece.
108+
Default chunk size: 1k."""
109+
while True:
110+
data = file_object.read(chunk_size)
111+
if not data:
112+
break
113+
yield data
114+
115+
with open('path/to/file', 'r') as f:
116+
for piece in read_in_chunks(f):
117+
print piece
118+
```
119+
120+
## 逐行读取
121+
122+
在某些情况下,我们希望逐行读取文件,这时可以使用 `readline()` 方法。
123+
124+
看看例子:
125+
126+
```python
127+
with open('data.txt', 'r') as f:
128+
while True:
129+
line = f.readline() # 逐行读取
130+
if not line:
131+
break
132+
print line, # 这里加了 ',' 是为了避免 print 自动换行
133+
```
134+
135+
执行结果:
136+
137+
```
138+
10 1 9 9
139+
6 3 2 8
140+
20 10 3 23
141+
1 4 1 10
142+
10 8 6 3
143+
10 2 1 6
144+
```
145+
146+
## 文件迭代器
147+
148+
在 Python 中,**文件对象是可迭代的**,这意味着我们可以直接在 for 循环中使用它们,而且是逐行迭代的,也就是说,效果和 `readline()` 是一样的,而且更简洁。
149+
150+
看看例子:
151+
152+
```python
153+
with open('data.txt', 'r') as f:
154+
for line in f:
155+
print line,
156+
```
157+
158+
在上面的代码中,f 就是一个文件迭代器,因此我们可以直接使用 `for line in f`,它是逐行迭代的。
159+
160+
看看执行结果:
161+
162+
```python
163+
10 1 9 9
164+
6 3 2 8
165+
20 10 3 23
166+
1 4 1 10
167+
10 8 6 3
168+
10 2 1 6
169+
```
170+
171+
再看一个例子:
172+
173+
```python
174+
with open(file_path, 'r') as f:
175+
lines = list(f)
176+
print lines
177+
```
178+
179+
执行结果:
180+
181+
```python
182+
['10\t1\t9\t9\n', '6\t3\t2\t8\n', '20\t10\t3\t23\n', '1\t4\t1\t10\n', '10\t8\t6\t3\n', '10\t2\t1\t6']
183+
```
184+
185+
可以看到,我们可以对文件迭代器执行和普通迭代器相同的操作,比如上面使用 `list(open(filename))` 将 f 转为一个字符串列表,这样所达到的效果和使用 `readlines` 是一样的。
186+
187+
# 写文件
188+
189+
写文件使用 `write` 方法,如下:
190+
191+
```python
192+
with open('/Users/ethan/data2.txt', 'w') as f:
193+
f.write('one\n')
194+
f.write('two')
195+
```
196+
197+
- 如果上述文件已存在,则会清空原内容并覆盖掉;
198+
- 如果上述路径是正确的(比如存在 /Users/ethan 的路径),但是文件不存在(data2.txt 不存在),则会新建一个文件,并写入上述内容;
199+
- 如果上述路径是不正确的(比如将路径写成 /Users/eth ),这时会抛出 IOError;
200+
201+
如果我们想往已存在的文件追加内容,可以使用 'a' 模式,如下:
202+
203+
```python
204+
with open('/Users/ethan/data2.txt', 'a') as f:
205+
f.write('three\n')
206+
f.write('four')
207+
```
208+
209+
# 小结
210+
211+
- 推荐使用 with 语句操作文件 IO。
212+
- 如果文件较大,可以按字节读取或按行读取。
213+
- 使用文件迭代器进行逐行迭代。
214+
215+
# 参考资料
216+
217+
- 《Python 基础教程》
218+
- [读写文本数据 — python3-cookbook 2.0.0 文档](http://python3-cookbook.readthedocs.io/zh_CN/latest/c05/p01_read_write_text_data.html)
219+
220+

0 commit comments

Comments
 (0)