Markus
Markus

Reputation: 175

'No such file or directory' with absolute Path

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] No such file or directory

Any suggestions for a python newbie?

At first I used relative Path, switched to absolute Path.

Upvotes: 0

Views: 2998

Answers (2)

RMPR
RMPR

Reputation: 3511

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)

You can check the full documentation of os.path here.

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)

Upvotes: 1

nheise
nheise

Reputation: 311

If you're using Windows, that path may cause issues because of the direction of the slashes. Check out this article. You shouldn't hardcode paths because regardless of which direction of slash you use, it can break on other operating systems.

It should work with something like this:

import os
import matplotlib.pyplot as plt

picture_path = os.path.join("C:", "Users", "myusername", "Downloads", "Mathe", "Picture.png")
im = plt.imread(picture_path)

Upvotes: 0

Related Questions