案例:

某文件系统目录下有一系列文件:

    1.c

    2.py

    3.java

    4.sh

    5.cpp

    ......

  编写一个程序,给其中所有的.sh文件和.py文件加上可执行权限

如何解决这个问题?

  1. 先获取目录下文件

  2. 通过startswith() 和endswith()方法判断是否以某个字符开头或结尾,列表解析留下满足条件的文件名

  3. 迭代列表,给对应的文件赋予权限

#!/usr/bin/python3

__author__ = 'beimenchuixue'
__blog__ = 'http://www.cnblogs.com/2bjiujiu/' import os
import stat def chmod_py(target_path):
# 获得当前文件下目录文件
file_l = os.linesdir(target_path) # startswith中拥有多个参数必须是元组形式,只需满足一个条件,返回True
target_file = [name for name in file_l if name.startswith(('.sh', '.py'))] for file in target_file:
# 给满足条件的文件所有者赋予执行权限
os.chmod(file, os.stat(file).st_mod | stat.S_IXUSR) if __name__ == '__main__':
# 目标目录
target_path = '.' chmod_py(target_path=target_path)

  

  判断字符是否以某个字符开头和结尾

# -*- coding: utf-8 -*-
# !/usr/bin/python3 __author__ = 'beimenchuixue'
__blog__ = 'http://www.cnblogs.com/2bjiujiu/' def check_str(value):
# 检查你输入的是否是字符类型
if isinstance(value, str):
# 判断字符串以什么结尾
if value.endswith('.sh'):
return '%s 是以.sh结尾的字符串' % value
# 判断字符串以什么开头
elif value.startswith('xi'):
return '%s 是以xi开头的字符串' % value
else:
return '%s 不满足以上条件的字符串' % value
else:
return '%s is not str' % value def main():
str_one = 'bei_men.sh'
resp_one = check_str(str_one)
print(resp_one) str_two = 'xi_du.py'
resp_two = check_str(str_two)
print(resp_two) str_three = 233
resp_three = check_str(str_three)
print(resp_three) if __name__ == '__main__':
main()

  

  

 

  

  

最新文章

  1. javascript的正则表达式学习
  2. torrent
  3. WEKA运行LIBSVM出现problem evaluating classifier:rand
  4. 让U盘永不中毒的解决办法
  5. MySQL模拟:线上误update的恢复
  6. Reference in the manifest does not match the identity of the downloaded assembly
  7. 学习C++ Primer 的个人理解(七)
  8. 《疯狂java讲义》笔记 1-5章
  9. 鼠标移入 移出div div会消失的处理
  10. CSS盒模型和margin重叠
  11. java中数组复制的两种方式
  12. linux C中调用shell命令和运行shell脚本
  13. Git使用基础介绍
  14. Rabbitmq 安装后采坑
  15. Mergeable Stack(链表实现栈)
  16. javaweb中的乱码问题
  17. 一个JS Class的“增删改查”
  18. 微信小程序新版用户授权方式处理
  19. HashMap实现原理(转)
  20. 2017年10月21日 数据库基础&三大范式

热门文章

  1. zabbix如何监控Nvidia显卡的各项指标?
  2. webdriver入门之环境准备
  3. Mac系统下php.ini的位置
  4. Tesseract OCR 安装尝试
  5. 9.深入k8s:调度器及其源码分析
  6. MyBatis-Plus分页——PageHelper和IPage介绍
  7. DSRC和USRP的购买调研
  8. Oracle中创建千万级大表归纳
  9. Nginx小功能合集
  10. Charles的几个用途