问题描述
我想导入一个 .png 文件
I want to import a .png file with
import matplotlib.pyplot as plt
O = plt.imread('C:/Users/myusername/Downloads/Mathe/Picture.png')
我有绝对路径,但它仍然给我错误:
I have the absolute Path, but it still gives me the Error:
[Errno 2] 没有那个文件或目录
对 Python 新手有什么建议吗?
Any suggestions for a python newbie?
一开始用的是相对路径,后来改用绝对路径.
At first I used relative Path, switched to absolute Path.
推荐答案
正如前面的回答所说,你不应该对路径进行硬编码,一般来说,要访问当前用户的主目录,你可以使用os.path.expanduser("~")
并通过一些输入控制,您的程序变成:
As stated by the previous answer, you shouldn't hard-code paths and in general, to access the home directory of the current user, you can use os.path.expanduser("~")
and with some input control, your program becomes:
import os
import matplotlib.pyplot as plt
picture_path = os.path.join(os.path.expanduser("~"), "Downloads", "Mathe",
"Picture.png")
if os.path.isfile(picture_path):
im = plt.imread(picture_path)
您可以在此处查看 os.path 的完整文档.
正如 Eryk Sun 在评论中指出的,虽然在这种情况下它可以工作,但在 Windows 中,实际上不建议使用 os.path.expanduser("~")
(即用户的配置文件目录在大多数情况下)因为大多数特殊路径(即已知文件夹)在 shell 中是可重定位的.使用 API 查询 Windows shell 以获取已知文件夹的路径(例如 FOLDERID_Downloads).There 有一个使用 PyWin32 这样做的示例,如果无法使用 Pywin32,则答案链接到使用 ctypes 的另一种方法.
As Eryk Sun noted in the comments, while in this case it works, In Windows, it's actually not advised to use os.path.expanduser("~")
(i.e. the user's profile directory in most cases) because most of the special paths (i.e. known folders) are relocatable in the shell. Use the API to query the Windows shell for the path of a known folder (e.g. FOLDERID_Downloads). There is an example to do so using PyWin32 and if it's not possible to use Pywin32, the answer links to another method using ctypes.
最后,你可能有这样的东西
Finally, you may have something like that
import matplotlib.pyplot as plt
import os
import pythoncom
from win32com.shell import shell
kf_mgr = None
def get_known_folder(folder_id):
global kf_mgr
if kf_mgr is None:
kf_mgr = pythoncom.CoCreateInstance(shell.CLSID_KnownFolderManager,None,
pythoncom.CLSCTX_INPROC_SERVER,
shell.IID_IKnownFolderManager)
return kf_mgr.GetFolder(folder_id).GetPath()
picture_path = os.path.join(get_known_folder(shell.FOLDERID_Downloads), "Mathe",
"Picture.png")
if os.path.isfile(picture_path):
im = plt.imread(picture_path)
这篇关于具有绝对路径的“没有这样的文件或目录"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!