【问题标题】:python - automatically launch a text file created in the programpython - 自动启动在程序中创建的文本文件
【发布时间】:2018-06-22 05:59:29
【问题描述】:

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

我正在使用 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)

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

【问题讨论】:

  • “启动文件”是什么意思?在文本编辑器中?
  • 是的,我正在创建文件为 *.txt 想用记事本或记事本++打开它
  • 这没有回答我的问题,你的文件应该如何启动?在什么文本编辑器中?它依赖于操作系统
  • 我使用的是 Windows 平台,而不是默认程序,我想用另一个程序打开它。
  • 看看subprocess 模块,尤其是subprocess.Popen

标签: python-3.x


【解决方案1】:

如果你知道命令行的方式,可以使用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

【讨论】:

  • 不好意思问你,你能解释一下吗,我用的是windows
  • @mortuzahasan 更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
  • 2020-02-05
  • 2022-07-13
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 2016-06-13
相关资源
最近更新 更多