案例:
某文件系統目錄下有一系列文件:
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()
