返回顶部

收藏

python验证文件是否可读可写

更多
# Import python libs
import os

def is_writeable(path, check_parent=False):
    '''
    Check if a given path is writeable by the current user.

    :param path: The path to check
    :param check_parent: If the path to check does not exist, check for the
           ability to write to the parent directory instead
    :returns: True or False
    '''

    if os.access(path, os.F_OK) and os.access(path, os.W_OK):
        # The path exists and is writeable
        return True

    if os.access(path, os.F_OK) and not os.access(path, os.W_OK):
        # The path exists and is not writeable
        return False

    # The path does not exists or is not writeable

    if check_parent is False:
        # We're not allowed to check the parent directory of the provided path
        return False

    # Lets get the parent directory of the provided path
    parent_dir = os.path.dirname(path)

    if not os.access(parent_dir, os.F_OK):
        # Parent directory does not exit
        return False

    # Finally, return if we're allowed to write in the parent directory of the
    # provided path
    return os.access(parent_dir, os.W_OK)

def is_readable(path):
    '''
    Check if a given path is readable by the current user.

    :param path: The path to check
    :returns: True or False
    '''

    if os.access(path, os.F_OK) and os.access(path, os.R_OK):
        # The path exists and is readable
        return True

    # The path does not exist
    return False

标签:python

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 小码哥 发表 2017-11-07 08:00:25 Python中的时间处理大总结
  2. 小码哥 发表 2017-11-07 08:19:22 如何快速爬取B站全站视频信息
  3. Gavin 发表 2017-11-06 10:01:37 Python批量给云主机配置安全组
  4. Gavin 发表 2017-11-06 10:06:40 如何使用pdb工具来调试python脚本?
  5. 博主 发表 2017-11-05 04:08:13 C语言实现的Python扩展模块
  6. 博主 发表 2017-11-04 14:40:16 Python 3 极简教程 之 基本数据类型
  7. zhu329599788@126 发表 2017-10-18 09:48:23 打印杨辉三角(python版)
  8. 小码哥 发表 2017-11-04 05:45:55 如何通过Python/Shell对HTTP服务状态的监控?
  9. techug 发表 2017-11-02 03:36:46 用Python复制文件的九种方法
  10. techug 发表 2017-11-03 03:46:27 python奇技淫巧
  11. gonwan 发表 2016-01-11 12:52:41 Coroutines in Python
  12. Charles 发表 2016-12-24 12:25:13 在 CentOS 6.8 上安装 Python 2.7

发表评论