美文网首页
测试文件是否存在

测试文件是否存在

作者: LittleBear_6c91 | 来源:发表于2019-05-09 20:46 被阅读0次

问题

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

解决方案

使用 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'
>>>

相关文章

  • 系统编程-文件操作3

    作业:在文件任意位置处插入数据 ACCESS(测试) 测试文件是否存在 测试文件是否有可读可写权限 测试文件是否有...

  • Python3 - 测试文件是否存在

    问题 测试文件是否存在 解决方案 使用 os.path 模块来测试一个文件或目录是否存在。比如: 还可以测试文件的...

  • 测试文件是否存在

    问题 你想测试一个文件或目录是否存在。 解决方案 使用 os.path 模块来测试一个文件或目录是否存在。比如: ...

  • 06_01_bash脚本编程之四 整数测试及特殊变量06_02_

    06_01_bash脚本编程之四 整数测试及特殊变量 文件测试(单目测试): -e file: 文件是否存在; -...

  • Pod小知识点

    验证 1、验证.podspec会先测试本地.podspec文件是否存在语法错误。测试成功再根据.podspec文件...

  • Linux基础学习八

    一:exit 1.exit 数字(退出状态码):退出脚本 文件测试: -e file:测试文件是否存在 -f fi...

  • 文件测试

    文件测试操作符 Perl提供了一组用于测试文件的操作符,并借此返回特定的文件信息。 -e测试文件是否存在 -M返回...

  • 验证podspec文件踩过的坑

    1、验证.podspec会先测试本地.podspec文件是否存在语法错误。测试成功再根据.podspec文件找到远...

  • Python 如何测试文件是否存在

    问题[https://www.bilibili.com/video/BV1LZ4y1H75S] 你想测试一个文件或...

  • node中fs操作方法总结

    1.测试某个路径下的文件是否存在 2.创建文件目录。如果目录已存在,将抛出异常 3.保存文件

网友评论

      本文标题:测试文件是否存在

      本文链接:https://www.haomeiwen.com/subject/knngoqtx.html