Ali Bahaari Ali Bahaari - 3 years ago 67
Python Question

How To Search More Carefully In Files With Python?

I get a file name from a user & upload the file for him/her, My problem is that due to my code, User should enter the file name to upload it, But I want to search more carefully & upload all files that their name is like the name user entered, How I can write it instead of this code?

Example : When user type Biology, The programm should upload files that are like Campbell Biology, My Biology Or ...

I need something LIKE Statement in SQL ...

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

Answer Source

It seems you want to get all files which contain the particular search string the user enters.

There are two options, the second one being more thorough than the first.

Option 1: glob.glob.

You can use the glob.glob function, passing wildcards:

import glob

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

Option 2: re.search with os.listdir:

You can traverse your present directory and filter with regex.

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 is limited by the wildcard syntax.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download