简体   繁体   English

如何为任何用户打开特定路径中的 Excel 文件?

[英]How to open an Excel file in a specific path for any user?

Goodafternoon,下午好,

Im opening an Excel file using Python:我使用 Python 打开 Excel 文件:

absolutePath = Path('C:\\Users\\jimmy\\Downloads\\Demo.csv').resolve()
os.system(f'start excel.exe "{absolutePath}"')

Sadly this only works for me, because my username is jimmy, for my colleague it doesn't work under his username.可悲的是,这只对我有用,因为我的用户名是 jimmy,对我的同事来说,它在他的用户名下不起作用。

How can I use this code on other computers with other usernames?如何在具有其他用户名的其他计算机上使用此代码?

Use relative paths to your python script:使用 python 脚本的相对路径:

import os
current_dir = os.path.dirname(__file__)
path_csv = os.path.join(current_dir, "Demo.csv")

absolutePath = Path(path_csv).resolve()
os.system(f'start excel.exe "{absolutePath}"')

Then place your python script in the same directory than your csv file.然后将 python 脚本与 csv 文件放在同一目录中。

You can get the username of the currently logged in user via os and then put that into the path string您可以通过 os 获取当前登录用户的用户名,然后将其放入路径字符串

import os
username = os.getenv("username")

absolutePath = Path(f'C:\\Users\\{username}\\Downloads\\Demo.csv').resolve()
os.system(f'start excel.exe "{absolutePath}"')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM