简体   繁体   English

Python 搜索部分文件名

[英]Python search for partial filename

I am using Python 3 and want to check for 2 things.我正在使用 Python 3 并想检查两件事。 Firstly I want to ensure there are 3 files in a directory, then I want to check that the 3 files match certain rules....首先我想确保一个目录中有 3 个文件,然后我想检查这 3 个文件是否符合某些规则....

  • 3 files in directory目录中的 3 个文件
  • A file called testfile1.txt一个名为 testfile1.txt 的文件
  • A file that matches myfile-*.txt (for example myfile-473spain.txt)与 myfile-*.txt 匹配的文件(例如 myfile-473spain.txt)
  • A file that matches newlog-*.log (for example newlog-55.log)与 newlog-*.log 匹配的文件(例如 newlog-55.log)

I have this so far...到目前为止我有这个...

list = os.listdir('myfiles') # dir is your directory path
number_files = len(list)

if number_files !=3 :
    print('Incorrect Number Of Files')
else:
    print('Correct Number Of Files')

if os.path.isfile('myfiles/testfile1.txt'):
    print ("myfiles/testfile1.txt - FOUND")
else:
    print ("myfiles/testfile1.txt - NOT FOUND")

But I am now stuck on how to search for the 2 partial match files.但我现在被困在如何搜索 2 个部分匹配文件上。 What can I try next?接下来我可以尝试什么?

Use glob.glob :使用glob.glob

import glob

if glob.glob('myfiles/myfile-*.txt'):
    print('match for "myfile-*.txt" found')
else:
    print('match for "myfile-*.txt" not found')

You could loop over the list you created in your first rule.您可以遍历您在第一条规则中创建的列表。 Then you could you the "in" statement: Something like:然后你可以使用“in”语句:类似于:

for fileName in list:
   if ("myfile-" in fileName and ".txt" in fileName):
      #OK

To match the beginning and end of a string, simply use the str.endswith and str.startswith.要匹配字符串的开头和结尾,只需使用 str.endswith 和 str.startswith。 If you want to do more complicated matching, look into the re module.如果您想做更复杂的匹配,请查看 re 模块。

file = 'myfile-something.txt'

if file.startswith('myfile-') and file.endswith('.txt'):
    print('success')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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