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 th
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)