首页 > 解决方案 > python - 自动启动在程序中创建的文本文件

问题描述

我进行了搜索,但找不到任何帮助,如果我的问题重复,我深表歉意。

我正在使用 python 3.6 和 windows 环境编写代码。在我的代码中,我打开了一个文本文件,写入数据并关闭文件。

self.fileName = 'file path'
self.log_file = open(self.fileName, 'w')
self.log_file.write('Write results')
self.lof_file.close()

而不是用户转到文件路径并单击打开它,我想在 python 保存文件后自动启动文件。

我怎么做?请帮忙

编辑:

os.startfile(filepath=self.fileName)

命令工作正常,但它使用默认程序记事本打开,如何使用特定程序打开文件,例如记事本++

标签: python-3.x

解决方案


如果你知道命令行的方式,你可以os按如下方式使用模块:

import os
self.file = 'file path'
self.log_file = open(self.fileName, 'w')
self.log_file.write('Write results')
self.lof_file.close()
os.system('gedit <file_path>')    # for ubuntu, gedit is generally present

对于 Windows,您可以使用:

import os
os.startfile('C:\\Users\\RandomUser\\Documents\\test.txt') 

检查此答案以获取更多详细信息:https ://stackoverflow.com/a/15055133/9332801


推荐阅读