如何修复“FileNotFoundError”,以便我只需输入文件名,而不是每次都输入一些荒谬的长文件路径?

问题描述 投票:0回答:1

vscode 中的简单 python 和终端中的 filenotfound 错误 每次尝试以这种方式或使用长文件路径引用文件时,我都会收到此错误。

我也尝试过使用 json 文件,但得到了相同的错误。我遵循了 youtube 上的一些教程,预计不会有任何问题,但我似乎找不到持久的解决方案。然而,Copilot 确实为我提供了一个解决方案,但我不想每次都依赖它,因为我不太理解它,我只是复制粘贴它并且它起作用了,但它是:

获取脚本当前目录

current_directory = os.path.dirname(os.path.abspath(file))

构建CSV文件的绝对路径

csv_file_path = os.path.join(current_directory,“googleplaystore.csv”)

python file
1个回答
0
投票

你应该使用这样的东西:

import os

script_dir = os.path.dirname(os.path.realpath(__file__))
filename = "your_file.txt"
file_path = os.path.join(script_dir, filename)

不管你是否愿意

cd /tmp
python /path/to/python/script.py

cd /path/to/python/
python script.py

script_dir
应该始终是
/path/to/python/

© www.soinside.com 2019 - 2024. All rights reserved.