简体   繁体   English

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

[英]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? 我是Python和Sublime Text API开发人员的新手,所以这可能很容易?

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! 谢谢你的帮助!

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. 在Sublime Text中,用于打开文件的内置API绑定到Window ,并将返回与选项卡相对应的View 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. 在您的情况下,您想使用文件内容更新面板(与选项卡无关的现有View ),因此Sublime Text API不能用于此目的。

Instead you can do it directly in Python using the open method : 相反,您可以使用open方法直接在Python中执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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