How can I search for files more thoroughly with Python?

I get the filename from the user and upload the file for him / her. My problem is that because of my code, the user has to enter the file name to download it, but I want to search more carefully and download all files that their name is similar to the entered username, how can I write it instead of this code?

Example: When custom type Biology, the program should load files similar to Campbell Biology, My Biology Or ​​...

I need something LIKE Statement in SQL ...

try:
    requested_file = open(str(args[0]) + '.pdf', 'rb')

      

+3


source to share


1 answer


You seem to want to get all files containing a specific search string that the user enters. There are two options, the second is more thorough than the first.

Option 1
You can use the function glob.glob

by passing wildcards:

import glob

search = ... # your term here
for files in glob.glob('*%s*.pdf' % search):
    ... # do something with file

      




Option 2
re.search

+ os.listdir

. You can move the current directory and filter using regular expression.

import os
import re

pattern = re.compile('.*%s.*\.pdf' %search, re.I)
for files in filter(pattern.search, os.listdir('.')):
    ... # do something with files

      

The second option offers you a little more flexibility. glob

limited to substitution syntax.

+1


source







All Articles