如何在 Sublime Text 3 中获取文件内容 Python API

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

我对 Python 和 Sublime Text API 开发还很陌生...所以这可能很简单?

我想将文件(位于当前打开的文件旁边)的内容显示到新面板 window。

我可以毫无问题地创建一个新面板,并使用

让它显示字符串
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

但我需要的是一个获取文件内容并传递给该函数的函数。

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

感谢您的帮助!

在 Sublime Text 中,用于打开文件的内置 API 绑定到 Window 并将 return 对应于选项卡的 View。在您的情况下,您想使用文件的内容更新面板(与选项卡无关的现有 View),因此不能使用 Sublime Text API .

您可以直接在 Python 中使用 open method:

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