Welcome, guest | Sign In | My Account | Store | Cart

Look into a folder along with subfolders for a file starting with or ending with certain characters.

Python, 52 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Required module
import os

# Function for getting files from a folder
def fetchFiles(pathToFolder, flag, keyWord):
	'''	fetchFiles() requires three arguments: pathToFolder, flag and keyWord
		
	flag must be 'STARTS_WITH' or 'ENDS_WITH'
	keyWord is a string to search the file's name
	
	Be careful, the keyWord is case sensitive and must be exact
	
	Example: fetchFiles('/Documents/Photos/','ENDS_WITH','.jpg')
		
	returns: _pathToFiles and _fileNames '''
	
	_pathToFiles = []
	_fileNames = []

	for dirPath, dirNames, fileNames in os.walk(pathToFolder):
		if flag == 'ENDS_WITH':
			selectedPath = [os.path.join(dirPath,item) for item in fileNames if item.endswith(keyWord)]
			_pathToFiles.extend(selectedPath)
			
			selectedFile = [item for item in fileNames if item.endswith(keyWord)]
			_fileNames.extend(selectedFile)
			
		elif flag == 'STARTS_WITH':
			selectedPath = [os.path.join(dirPath,item) for item in fileNames if item.startswith(keyWord)]
			_pathToFiles.extend(selectedPath)
			
			selectedFile = [item for item in fileNames if item.startswith(keyWord)]
			_fileNames.extend(selectedFile) 
			    
		else:
			print fetchFiles.__doc__
			break
						
		# Try to remove empty entries if none of the required files are in directory
		try:
			_pathToFiles.remove('')
			_imageFiles.remove('')
		except ValueError:
			pass
			
		# Warn if nothing was found in the given path
		if selectedFile == []: 
			print 'No files with given parameters were found in:\n', dirPath, '\n'
		
	print len(_fileNames), 'files were found is searched folder(s)'
				
	return _pathToFiles, _fileNames

Use this to get a python list of files with a certain name. By iterating over the list one can call a function upon those files. One can create a stand alone module with this code. This code does not support regular expressions in the searched keyword and can be improved using the python fnmatch module. The python glob module can do all this and then some, from python version 3.4 onwards.

Created by Sam Khan on Mon, 10 Jun 2013 (MIT)
Python recipes (4591)
Sam Khan's recipes (1)

Required Modules

Other Information and Tasks