如何正确设置Python项目的主要工作目录

发布于 2025-01-17 23:24:59 字数 633 浏览 2 评论 0原文

让我们假设我具有以下文件夹结构:

/path/to/project/directory/
|- MyProject/
   |- Scripts/
      |- Analysis/
         |- myanalysis.py
      |- Modelling/
         |- mymodel1.py
         |- mymodel2.py
         |- mymodel3.py
      |- Testing/
         |- mytest.py
      |- Function/
         |- myfunction.py
   |- Files/
      |- data.csv

我想在运行任何Python脚本时实现这一目标,工作目录始终将自动设置为/path/to/project/project/directory/directory/myproject。它应该是一个相对路径,以便其他人也可以运行脚本。实现这一目标的最佳实践是什么?我需要添加配置或INI文件吗?如果是,此文件将如何看起来像?

我来自R背景,您可以在其中设置R-projects,这些R-Project会自动将工作目录设置为R-Project文件的文件位置。我想取得这样的目标。

谢谢!

Let us assume I have the following folder structure:

/path/to/project/directory/
|- MyProject/
   |- Scripts/
      |- Analysis/
         |- myanalysis.py
      |- Modelling/
         |- mymodel1.py
         |- mymodel2.py
         |- mymodel3.py
      |- Testing/
         |- mytest.py
      |- Function/
         |- myfunction.py
   |- Files/
      |- data.csv

I want to achieve that when running any of the Python scripts, the working directory is always automatically set to /path/to/project/directory/MyProject. It should be a relative path such that someone else can also run the scripts. What would be the best practice to achieve that? Would I need to add a config or ini file? If yes, how would this file need to look like?

I am coming from a R background where you can set R-Projects which automatically set the working directory to the file location of the R-Project file. I want to achieve something like that.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可是我不能没有你 2025-01-24 23:24:59

许多选项:

  1. 创建虚拟env,声明一个变量(在.env文件上),并随时使用它
  2. 来创建一个config.py文件并在任何地方导入

  3. #run在您的代码之前设置当前路径
    #(创建一个在一切之前执行执行的函数)
    OS.CHDIR(Default_path)

Many options:

  1. Create virtual env, declare a variable (on a .env file) and use it always as needed
  2. Create a configs.py file and import it everywhere
  3. import os
    #run this before your code to set current path
    #(create a function that executes before everything)
    os.chdir(default_path)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文