Skip to content

Commit 32345e3

Browse files
committed
Add 5.12 测试文件是否存在
1 parent b66030f commit 32345e3

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# 5.12 测试文件是否存在
2+
3+
## 问题
4+
5+
你想测试一个文件或目录是否存在。
6+
7+
## 解决方案
8+
9+
使用 `os.path` 模块来测试一个文件或目录是否存在。比如:
10+
11+
```python
12+
>>> import os
13+
>>> os.path.exists('/etc/passwd')
14+
True
15+
>>> os.path.exists('/tmp/spam')
16+
False
17+
>>>
18+
```
19+
20+
你还能进一步测试这个文件时什么类型的。 在下面这些测试中,如果测试的文件不存在的时候,结果都会返回False:
21+
22+
```python
23+
>>> # Is a regular file
24+
>>> os.path.isfile('/etc/passwd')
25+
True
26+
27+
>>> # Is a directory
28+
>>> os.path.isdir('/etc/passwd')
29+
False
30+
31+
>>> # Is a symbolic link
32+
>>> os.path.islink('/usr/local/bin/python3')
33+
True
34+
35+
>>> # Get the file linked to
36+
>>> os.path.realpath('/usr/local/bin/python3')
37+
'/usr/local/bin/python3.3'
38+
>>>
39+
```
40+
41+
如果你还想获取元数据(比如文件大小或者是修改日期),也可以使用 `os.path` 模块来解决:
42+
43+
```python
44+
>>> os.path.getsize('/etc/passwd')
45+
3669
46+
>>> os.path.getmtime('/etc/passwd')
47+
1272478234.0
48+
>>> import time
49+
>>> time.ctime(os.path.getmtime('/etc/passwd'))
50+
'Wed Apr 28 13:10:34 2010'
51+
>>>
52+
```
53+
54+
## 讨论
55+
56+
使用 `os.path` 来进行文件测试是很简单的。 在写这些脚本时,可能唯一需要注意的就是你需要考虑文件权限的问题,特别是在获取元数据时候。比如:
57+
58+
```python
59+
>>> os.path.getsize('/Users/guido/Desktop/foo.txt')
60+
Traceback (most recent call last):
61+
File "<stdin>", line 1, in <module>
62+
File "/usr/local/lib/python3.3/genericpath.py", line 49, in getsize
63+
return os.stat(filename).st_size
64+
PermissionError: [Errno 13] Permission denied: '/Users/guido/Desktop/foo.txt'
65+
>>>
66+
```

0 commit comments

Comments
 (0)