sherry
sherry

Reputation: 21

Find file by part of filename in python

I need to search by part of filenames.

I have a column in my database that contains the names of products, and each product has a file for description, so I need to add this file to the same raw in my database.

I want to add a new column called description and add the contents of the file that has the same name on the column name, but the names in column and file are different, for example, the product called cs12 in the database and datasheet-cs12 or guide-cs12 or anything like this in the file

Upvotes: 1

Views: 678

Answers (1)

Marcus Müller
Marcus Müller

Reputation: 36462

You will need to figure out how to

  1. get a list of files in a folder
  2. Look for a substring in each element of that list

Re 1.: https://stackoverflow.com/search?q=%5Bpython%5D+get+list+of+files+in+directory

Re 2.:

You have a logical problems. There might be multiple files that match any string. So, I don't think you can solve this fully automatically at all. What if you have two files datasheet_BAT54alternative.txt and info_BAT54A, and two rows containing the string BAT54 and BAT54A. A "BAT54" is not the same as a "BAT54A". So, you'll always have to deal with a list of candidates. If you're lucky, that list has only one entry:

def give_candidates(list_of_file_names, substring):
    return [ fname for fname in file_names if substring.lower() in fname.lower() ]

Upvotes: 1

Related Questions