【问题标题】:Forced to enter full pathname every time instead of just file name每次都强制输入完整路径名,而不仅仅是文件名
【发布时间】:2021-06-01 15:00:27
【问题描述】:

每次我尝试执行诸如在 VScode 终端中运行程序(也发生在 PyCharm 中)之类的操作时,我都必须输入完整的路径名,而不仅仅是文件名。例如,我不能只输入python3 test.py 来运行程序,而必须输入python3 /Users/syedrishad/Desktop/Code/test.py

现在,这很烦人,但它并没有给我太多困扰。困扰我的是当我的程序试图从其他地方拉/打开文件时。如果我想要一个名为 Apple.jpeg 的图像,而不是仅仅输入 Apple.jpeg,我必须去找它的完整路径名。如果我将执行此操作的一段代码上传到 GitHub 之类的地方,想要自己测试此代码的人将不得不进去并仅用文件名替换每个路径名,否则它将无法正常工作他们的电脑。这个问题已经持续了一段时间,遗憾的是我还没有找到解决方案。我会很感激我得到的任何帮助。如果有什么不同的话,我也在使用 Mac。

【问题讨论】:

标签: python file pathname


【解决方案1】:

在 VS Code 中,其内部终端默认在当前打开的项目文件夹中。因此,当您使用命令“python file_name.py”运行该文件时,终端找不到内部文件夹中存在的文件。 因此,除了使用文件路径,我们还可以添加相关设置来帮助它找到文件。

运行:当使用运行按钮执行文件时,我们可以在“settings.json”中添加如下设置,它会自动进入执行文件的父文件夹。

"python.terminal.executeInFileDir": true,

"在终端执行文件时,是否使用在文件所在目录执行,而不是在当前打开的文件夹中执行。"

debug:为了调试代码,我们需要在“launch.json”中添加如下设置:

 "cwd": "${fileDirname}",

【讨论】:

    【解决方案2】:

    您可以使用 os 和 sys 为您提供 Python 文件所在文件夹的完整路径。
    sys 为您提供路径,os 为您提供将其与文件名合并的可能性。

    import sys, os
    print(sys.path[0]) # that is the path to the directory of the python file
    print(sys.path[0]+'/name.txt') #full path to the file
    print(os.path.join(sys.path[0],'name.txt')) # os.path.join takes two parameters and merges them as one path using / but the line above is also fine
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-15
      • 2016-08-16
      • 1970-01-01
      • 2012-03-10
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多