以下是一个实现这个功能:
import os
import subprocess
import sys
def open_file_location_and_select(file_path):
if not os.path.exists(file_path):
print("文件不存在")
return
if sys.platform == 'win32':
# 在 Windows 上打开文件所在位置并高亮显示该文件
subprocess.run(f'explorer /select,"{file_path}"', shell=True)
elif sys.platform == 'darwin':
# 在 macOS 上打开文件所在位置并高亮显示该文件
subprocess.run(['open', '-R', file_path])
else:
# 在 Linux 上,通常没有直接选中文件的功能,但可以打开目录
directory = os.path.dirname(os.path.abspath(file_path))
subprocess.run(['xdg-open', directory])
# 示例用法
file_path = 'example.txt' # 替换为你的文件路径
open_file_location_and_select(file_path)