Python_ How can I tell if string a starts or ends with a string?

Source: Internet
Author: User

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?

    1. Get the file in the directory first
    2. 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
    3. 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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.