matinal:python打开文件、文件夹窗口、终端窗口

本文介绍了如何使用Python在Windows和Linux系统中,分别通过os.system和subprocess.Popen等方法打开文件、文件夹以及启动终端。详细展示了在不同操作系统上执行相应命令的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

在一些项目中,我们会需要在生成完文件后打开某些文件或者文件夹窗口,这就需要使用到内置的文件打开方式了。

打开文件或文件夹

Windows

import os
import subprocess


# 打开文件或者速度最快, 推荐,不过只适用于Windows
def start_file(file_path):
    os.startfile(file_path)


# 打开文件或文件夹,到对应文件或者文件夹时只会选中,不会进入到内部, 只适用于Windows
def start_file2(file_path):
    subprocess.Popen(f'explorer /select,"{file_path}"')


# 与第一种功能类似,只适用于Windows
def start_file3(file_path):
    # os.system(f"start {file_path}")
    subprocess.Popen(f"start {file_path}", shell=True)


file_path = r"D:\1.gif"
# start_file(file_path)
# start_file2(file_path)
start_file3(file_path)

Linux

os.system('xdg-open "%s"' % foldername)

打开终端并输入内容

Linux

os.system("gnome-terminal -e 'ls'")

Windows

os.system("start powershell.exe cmd /k 'dir'")

引号中内容为执行的命令

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值