打开某文件夹下指定类型文件,以txt文件为例
import os
import subprocess
def open_txt_files_in_folder(folder_path):
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
try:
# 拼接文件的绝对路径
open_file_path = os.path.join(folder_path, filename)
open_file(open_file_path)
except Exception as e:
print(f"Error opening file {filename}: {str(e)}")
def open_file(file_path):
try:
if platform.system() == 'Windows':
os.startfile(file_path)
elif platform.system() == 'Darwin': # macOS
subprocess.run(['open', file_path])
else: # Linux and other Unix-like systems
subprocess.run(['xdg-open', file_path])
except Exception as e:
print(f"Failed to open file {file_path}. Error: {e}")