5.12 测试文件是�存在¶

问题¶

你想测试一个文件或目录是�存在。

解决方案¶

使用 os.path 模��测试一个文件或目录是�存在。比如:

>>> import os
>>> os.path.exists('/etc/passwd')
True
>>> os.path.exists('/tmp/spam')
False
>>>

你还能进一步测试这个文件时什么类型的。 在下�这些测试中,如果测试的文件�存在的时候,结果都会返回False:

>>> # Is a regular file
>>> os.path.isfile('/etc/passwd')
True

>>> # Is a directory
>>> os.path.isdir('/etc/passwd')
False

>>> # Is a symbolic link
>>> os.path.islink('/usr/local/bin/python3')
True

>>> # Get the file linked to
>>> os.path.realpath('/usr/local/bin/python3')
'/usr/local/bin/python3.3'
>>>

如果你还想获�元数�(比如文件大�或者是修改日期),也�以使用 os.path 模��解决:

>>> os.path.getsize('/etc/passwd')
3669
>>> os.path.getmtime('/etc/passwd')
1272478234.0
>>> import time
>>> time.ctime(os.path.getmtime('/etc/passwd'))
'Wed Apr 28 13:10:34 2010'
>>>

讨论¶

使用 os.path �进行文件测试是很简�的。 在写这些脚本时,�能唯一需�注�的就是你需�考虑文件��的问题,特别是在获�元数�时候。比如:

>>> os.path.getsize('/Users/guido/Desktop/foo.txt')
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/local/lib/python3.3/genericpath.py", line 49, in getsize
        return os.stat(filename).st_size
PermissionError: [Errno 13] Permission denied: '/Users/guido/Desktop/foo.txt'
>>>