简体   繁体   中英

Python Lambda File Sorting/Restriction

I and reading in a directory of files and I'm trying to filter out files based on if a string exists in the file name or not, so I have two file name types:

  • till_20200810150309.gz
  • flod_20200810150310.gz

The below code snippet reads in the files ok, but I'm trying to only limit it to till files, it's currently returning all files found in the directory and not filtering out just the till ones.

files = sorted([f for f in os.listdir(root_directory) if os.path.isfile(os.path.join(root_directory, f)) and f.endswith('.gz')], key=lambda x: x if "till" in x else "")

Using more or less the same strategy you can add a third condition:

files = sorted([f for f in os.listdir(root_directory) if os.path.isfile(os.path.join(root_directory, f)) and f.endswith('.gz') and f.startswith("till")])

That will limit the files to only those starting with till.

You also don't need to setup a key to sort since you want it done based on the file name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM