python determines if an instance of the specified suffix file exists in the folder

  • 2021-06-28 09:32:20
  • OfStack

This code is primarily based on the python implementation to determine whether a file with the specified suffix exists in a specified folder.The code is as follows:


import os
 
Your_Dir=' Your Folder /'
Files=os.listdir(Your_Dir)
for k in range(len(Files)):
  #  Extract suffixes for all files in a folder 
  Files[k]=os.path.splitext(Files[k])[1]
 
Str2=['.wav','.mp3','.mp4']
if len(list(set(Str2).intersection(set(Files))))==len(Str2):
  return True
else:
  return False

The code above can tell if there is one or more suffixes specified at the same time.It is also possible to determine if only one of the specified suffixes exists:


import os
 
Your_Dir='D:/python data /01linux Basic Video / Course Video /'
Files=os.listdir(Your_Dir)
for k in range(len(Files)):
  #  Extract suffixes for all files in a folder 
  Files[k]=os.path.splitext(Files[k])[1]
 
#  The suffix of the file you want to find 
Str='.mp4'
if Str in Files:
  return True
else:
  return False

The os.path.splitext() function in the code mainly separates the file name from the file suffix.For example, the file name of a file is:


file='123.wav'
      be os.path.splitext(file)[0] = '123' ; os.path.splitext(file)[1] ='.wav'

If there is something wrong, point it out.


Related articles: