Python验证文件是否可读写代码分享

yipeiwu_com5年前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验证文件是否可读写代码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

Python文件操作基本流程代码实例

Python实现读取txt文件并画三维图简单代码示例

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Pyinstaller打包.py生成.exe的方法和报错总结

Pyinstaller 打包.py生成.exe的方法和报错总结 简介 有时候自己写了个python脚本觉得挺好用想要分享给小伙伴,但是每次都要帮他们的电脑装个python环境。虽然说装一...

python利用thrift服务读取hbase数据的方法

因工作需要用python通过hbase的thrift服务读取Hbase表数据,发现公司的测试环境还不支持,于是自己动手准备环境,在此我将在安装步骤尽可能描述清楚,旨在给第一次动手安装的朋...

python图像处理之反色实现方法

python图像处理之反色实现方法

本文实例讲述了python图像处理之反色实现方法。分享给大家供大家参考。具体如下: 我们先加载一个8位灰度图像 每一个像素对应的灰度值从0-255 则只需要读取每个像素的灰度值A,再将2...

Laravel框架表单验证格式化输出的方法

Laravel框架表单验证格式化输出的方法

最近在公司的项目开发中使用到了 laravel 框架,采用的是前后端开发的模式。接触过前后端开发模式的小伙伴应该都知道,后端返回的数据格式需要尽可能搞得保证一致性,这样前端在处理时也方...

Python简单日志处理类分享

简单的一个python日志处理类 复制代码 代码如下: #/usr/bin/python #coding=utf-8 import time,types class logsys: &n...