如何测试Python中是否存在文件或目录?

In Bash, the [ -f ] and [ -d ] tests can test whether a file or a directory exist. What are the corresponding python method for these tests?

在Bash中, [ -f ][ -d ]测试可以测试文件或目录是否存在。 这些测试对应的python方法是什么?

For -f:

对于-f

**os.path.isfile(path)**

Return True if path is an existing regular file. This follows symbolic links.

如果path是现有的常规文件,则返回True。 这遵循符号链接。

For -d:

对于-d

**os.path.isdir(path)**

Return True if path is an existing directory. This follows symbolic links.

如果path是现有目录,则返回True。 这遵循符号链接。

As they follow symbolic links (in Bash, -d and -f do too), if you are interested filter symbolic links out, you can use

由于它们遵循符号链接(在Bash中, -d-f也是如此),如果您有兴趣过滤掉符号链接,则可以使用

**os.path.islink(path)**

Return True if path refers to a directory entry that is a symbolic link. Always False if symbolic links are not supported by the python runtime.

如果path引用的目录条目是符号链接,则返回True。 如果python运行时不支持符号链接,则始终为False。

Answered by Eric Z Ma.
埃里克·马(Eric Z Ma)回答。

翻译自: https://www.systutorials.com/how-to-test-a-file-or-directory-exists-in-python/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值