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文件并画三维图简单代码示例

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

相关文章

15行Python代码实现网易云热门歌单实例教程

15行Python代码实现网易云热门歌单实例教程

0. 引言 马上314情人节就要来了,是否需要一首歌来抚慰你,受伤或躁动的心灵。来吧,今天教你用15行代码搞定热门歌单。学起来并听起来吧。 本文使用的是Selenium模块,它是一个自...

Python新手在作用域方面经常容易碰到的问题

通常,当我们定义了一个全局变量(好吧,我这样说是因为讲解的需要——全局变量是不好的),我们用一个函数访问它们是能被Python理解的:   bar = 42 def fo...

python删除文本中行数标签的方法

python删除文本中行数标签的方法

问题描述: 我们在网上下载或者复制别人代码的时候经常会遇到下载的代码中包含行数标签的情况。如下图: 这些代码中包含着行数如1.,2.等,如果我们想直接运行或者copy代码需要自己手动的...

Python中elasticsearch插入和更新数据的实现方法

Python中elasticsearch插入和更新数据的实现方法

    首先,我的索引结构是酱紫的。          存储以name_id为主键的索引,待插...

python中virtualenvwrapper安装与使用

virtualenv与virtualenvwrapper 当涉及到python项目开发时为了不污染全局环境,通常都会使用环境隔离管理工具virtualenv与virtualenvwra...