Skip to content

Commit 3a3bc19

Browse files
committed
add 5.5 文件不存在才能写入
1 parent 98d4c0e commit 3a3bc19

File tree

5 files changed

+56
-0
lines changed

5 files changed

+56
-0
lines changed

PythonCookbook3rd/part5文件IO/p01_write_to_file.md

Whitespace-only changes.
File renamed without changes.
File renamed without changes.
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# 5.5 文件不存在才能写入
2+
3+
## 问题
4+
5+
你想像一个文件中写入数据,但是前提必须是这个文件在文件系统上不存在。 也就是不允许覆盖已存在的文件内容。
6+
7+
## 解决方案
8+
9+
可以在 `open()` 函数中使用 `x` 模式来代替 `w` 模式的方法来解决这个问题。比如:
10+
11+
```python
12+
>>> with open('somefile', 'wt') as f:
13+
... f.write('Hello\n')
14+
...
15+
>>> with open('somefile', 'xt') as f:
16+
... f.write('Hello\n')
17+
...
18+
Traceback (most recent call last):
19+
File "<stdin>", line 1, in <module>
20+
FileExistsError: [Errno 17] File exists: 'somefile'
21+
>>>
22+
```
23+
24+
如果文件是二进制的,使用 `xb` 来代替 `xt`
25+
26+
## 讨论
27+
28+
这一小节演示了在写文件时通常会遇到的一个问题的完美解决方案(不小心覆盖一个已存在的文件)。 一个替代方案是先测试这个文件是否存在,像下面这样:
29+
30+
```python
31+
>>> import os
32+
>>> if not os.path.exists('somefile'):
33+
... with open('somefile', 'wt') as f:
34+
... f.write('Hello\n')
35+
... else:
36+
... print('File already exists!')
37+
...
38+
File already exists!
39+
>>>
40+
```
41+
42+
如果不存在,则输出写入文件大小
43+
44+
```python
45+
>>> import os
46+
>>> if not os.path.exists('somefile'):
47+
... with open('somefile', 'wt') as f:
48+
... f.write('Hello\n')
49+
... else:
50+
... print('File already exists!')
51+
...
52+
6
53+
>>>
54+
```
55+
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
hello

0 commit comments

Comments
 (0)