Case:
A file system directory has a series of files:
1.c
2.py
3.java
4.sh
5.cpp
......
Write a program that adds executable permissions to all of these. sh files and. py files
How to solve this problem?
- Get the file in the directory first
- Determine whether to end with a character by using the StartsWith () and EndsWith () methods, and list parsing leaves a file name that satisfies the criteria
- Iterate lists, assigning permissions to the corresponding files
#!/usr/bin/python3import Osimport stat# get current file under directory file_l = Os.linesdir ('. ') # StartsWith parameter must be a tuple form, only one condition is met, return truetarget_file = [name for name in file_l if Name.startswith (('. Sh ', '. Py '))]for file I n target_file: # gives execute permission to the file owner that satisfies the condition os.chmod (file, Os.stat (file). st_mod | Stat. S_IXUSR)
Python_ How can I tell if string a starts or ends with a string?