简体   繁体   中英

how to open a file closest to the file specified python

I am using python and I wand to run a program the will open the file specified by the user. But the problem is that, if the user doesn't specify the exact file name, then it will give an error. If the user wants to open "99999-file-name.mp3" and he has typed "filename.mp3", then how can the program open the file closest to the one specified?

First get a list of files in the particular folder

Then use difflib.get_close_matches like so:

difflib.get_close_matches(user_specified_file, list_of_files)

to find "good" matches.

NB: Consider putting a providing a small cutoff ie 0.1 as suggested by @tobias_k to ensure you do you get a match always as the default cutoff of 0.6 means sometimes nothing will be a "good match" for what the user entered.

Similarly if you need to get only one file name also pass in the optional parameter n=1 to get the closest match since if you don't specify it you will get the 3 best matches.

To answer this question, you need to first define "closest" because in computing this can mean very different things. If you want to compare strings and find the most similar, then one good way of doing that is checking the edit distance. There are Python libraries out there for that, ie https://pypi.python.org/pypi/editdistance .
You give it two strings and it tells you how much you have to change one string to get the other. As per the documentation:

>>> import editdistance
>>> editdistance.eval('banana', 'bahama')
2L

PS. Can't help but to mention that I think this is a bad idea. If you want to do sth with the file opened and the program starts opening random files, then either you're eventually gonna overwrite a file that is not meant to be overwritten or you try to process a file that can't be processed in your intended way. I would recommend using a file select box that you can easily use with tKinter for example (even though tKinter is cancer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM