Search code examples
pythonsublimetext3sublimetextsublime-text-plugin

How to get contents of file in Sublime Text 3 Python API


I'm very new to Python and Sublime Text API dev... so this may be easy?

I want to display the contents of a file (that sits next to the currently open file) to a new panel window.

I can create a new panel no problem and get it to display a string using

def newLogWindow(self, output):
    window = self.view.window()

    new_view = window.create_output_panel("log")
    new_view.run_command('erase_view')
    new_view.run_command('append', {'characters': output})
    window.run_command("show_panel", {"panel": "output.log"})

    sublime.status_message('Metalang')

pass

But what I need is a function to get contents of file to pass to that function.

content = xxxx.open_file("filename.txt")
// somehow get contents of this file?
// pass it to log window
self.newLogWindow(content);

Thanks for your help!


Solution

  • In Sublime Text, the built in API to open a file is tied to the Window and will return a View that corresponds to a tab. In your case, you want to update a panel (an existing View that doesn't relate to a tab) with the contents of the file, so the Sublime Text API can't be used for this.

    Instead you can do it directly in Python using the open method:

    with open('filename.txt', 'r') as myfile:
        content = myfile.read()
        self.newLogWindow(content)