python - 每次都强制输入完整路径名,而不仅仅是文件名
问题描述
每次我尝试执行诸如在 VScode 终端中运行程序(也发生在 PyCharm 中)之类的操作时,我都必须输入完整的路径名,而不仅仅是文件名。例如,我不仅python3 test.py
要运行程序,还必须输入python3 /Users/syedrishad/Desktop/Code/test.py
.
现在,这很烦人,但它并没有太困扰我。困扰我的是当我的程序试图从其他地方拉/打开文件时。如果我想要一个名为 Apple.jpeg 的图像,而不是仅仅输入 Apple.jpeg,我必须去找它的完整路径名。如果我将执行此操作的一段代码上传到 GitHub 之类的地方,想要自己测试此代码的人将不得不进去并仅用文件名替换每个路径名,否则它将无法正常工作他们的电脑。这个问题已经持续了一段时间,遗憾的是我还没有找到解决方案。我会很感激我得到的任何帮助。如果这有所作为,我也在 Mac 上。
解决方案
您可以使用 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
推荐阅读
- c++ - 我可以阻止用户在后台运行我的 C++ 程序吗?
- python - TypeError:“NoneType”对象不可迭代(h5 文件)
- kubernetes - _condition_ 在公制中是什么意思?
- google-cloud-platform - 需要帮助在 Google Cloud 上设置 A 记录
- android - Kotlin Android 扩展 - 合成属性在支持片段中不可用
- java - 删除user id下的单个child,随机生成childname,android studio,firebase
- r - 修改列表和环境
- android - Android Studio 非法状态异常:找不到 android:onClick 的方法(视图)
- python - python - cx_Freeze ImportError
- php - 按包含逻辑运算符的键对数组进行排序