首页 > 解决方案 > 每次都强制输入完整路径名,而不仅仅是文件名

问题描述

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

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

标签: pythonfilepathname

解决方案


您可以使用 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

推荐阅读