简体   繁体   中英

Python in Sublime Text 3: oslist dir; list specific extensions only

I'm trying to make a small tweak to this Sublime Text 3 plugin making this is my first foray into Python.

The plugin provides a list of Markdown files when the command [[ is entered in the keyboard. The thing is that other files show up on the list that I do not want to appear!

From what I've gathered, the bulk of the command demands on os.listdir(directory) . I'm aware that trying to list only specific extensions with os.listdir has been inquired of previously such as here and here , but I just don't understand how to go about implementing those answers into the code that I have. Like others have sought, I'm trying to figure out how to show only .md files using os.listdir, but the exception is that I'm looking to do so in the scope of this plugin.

The code for the plugin in it's entirety is available here .

Below is an excerpt that includes what I would imagine is the more relevant details of my dilemma.

class GetWikiLinkCommand(sublime_plugin.TextCommand):
    def on_done(self, selection):
        if selection == -1:
            self.view.run_command(
                "insert_wiki_link", {"args":
                {'text': '[['}})
            return
        self.view.run_command(
            "insert_wiki_link", {"args":
            {'text': '[['+self.modified_files[selection]+']]'}})

    def run(self, edit):
        settings = sublime.load_settings('MyWiki.sublime-settings')
        directory = settings.get('wiki_directory')
        directory = os.path.expanduser(directory)
        extension = settings.get('wiki_extension')

        self.outputText = '[['
        self.files = os.listdir(directory) 
        self.modified_files = [item.replace(extension,"") for item in self.files]
        self.view.window().show_quick_panel(self.modified_files, self.on_done)

Thank you!!!

Probably the simplest fix is to change this line:

self.files = os.listdir(directory)

to

self.files = [f for f in os.listdir(directory) if f.endswith('.md')]

Alternatively, if you add glob and os.path to the import statement, you could do:

self.files = [os.path.basename(p) for p in glob.glob(os.path.join(directory, '*.md'))]

which might be more performant, if glob is able to filter files faster - not sure about that.

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