[英]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 个文件是否符合某些规则....
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?接下来我可以尝试什么?
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.