How to load an icon using relative path in python [duplicate] - python

This question already has answers here:
Using QIcon does not display the image
(2 answers)
Closed 1 year ago.
I created a package that contains an icon.png inside a resource-folder:
../mypackage/resource/icon.png
../mypackage/qtprogram.py
I am now trying to access the icon.png in qtprogram.py. As they are both in mypackage directory, I tried using:
QtGui.QIcon("resource//icon.png")
but it did not work. However, using the full path (in relation to the main script path) did. Since this should be a shareable package, I would like to avoid using the full path. How can I do this?

I think it should be \\ (or) r'relative-path-to-file' instead of // in QtGui.QIcon("resource//icon.png").
I would use the os library.
import os
# If you plan to use to without PyInstaller
icon_path = os.path.join(os.path.dirname(__file__), r'resources\icon.png')
# If you plan to use to pyinstaller
icon_path = os.path.join(os.path.abspath(os.getcwd()), r'resources\icon.png')

Related

No such file or directory found, Python [duplicate]

This question already has answers here:
Open file in a relative location in Python
(14 answers)
Closed 7 months ago.
I'm new to coding so I followed a tutorial for a chatbot, I need to import my intentions (which I named intentii, in my language) intentii.json into the chatbot, so I'm using:
intentii = json.loads(open('intentii.json').read())
I have seen other questions about the error I said in the title, and yes, I made sure the name is typed right, it's in the same exact directory as all my files including this chatbot one are, and still, it says it can't find the file, I tried placing the whole directory path and it seemed to work ( I didn't get the same error again, but an unicode error which I believe is another problem related to my .json file ), but I cannot use the whole path because I have to send this to my teacher and, of course, he won't have the same exact path as mine.
What is the solution?
Edit: Also, I've noticed that it says that for every file I need to access from the folder
Try this function to load a json file:
import json
def load_json(filepath):
with open(filepath) as f:
data = json.load(f)
return data
Then
intentii = load_json("intentii.json")
Try using this python os module to find dir_root where current file is located and then combine it json file name if it is stored in same directory.
import json
import os
dir_root = os.path.dirname(os.path.abspath(__file__))
intentii1 = json.loads(open(dir_root+'\js.json').read())

How do I move a text file to a different folder? [duplicate]

This question already has answers here:
How to move a file in Python?
(11 answers)
Closed 2 years ago.
I already know how to create and write a text file in Python, but how do I move that file to a different folder on my system?
You can either make a system call with os.system:
import os
os.system("mv /path/to/file /path/to/destination")
or rename it:
os.rename("/path/to/file", "/path/to/destination")
or move it with `shutil.move`:
```python
import shutil
shutil.move("/path/to/file", "/path/to/destination")
First solution works only in bash shells, second and third should be portable over all platforms. Third has the advantage that you can specify a folder as destination, the file will then be put into that folder with the same name as in the old location.

Python check if a directory exists, then create it if necessary and save graph to new directory? [duplicate]

This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Closed 5 years ago.
so I want this to be independent of the computer the code is used on, so I want to be able to create a directory in the current directory and save my plots to that new file. I looked at some other questions and tried this (I have two attempts, one commented out):
import os
from os import path
#trying to make shift_graphs directory if it does not already exist:
if not os.path.exists('shift_graphs'):
os.mkdirs('shift_graphs')
plt.title('Shift by position on '+str(detector_num)+'-Detector')
#saving figure to shift_graphs directory
plt.savefig(os.path.join('shift_graphs','shift by position on '+str(detector_num)+'-detector'))
print "plot 5 done"
plt.clf
I get the error :
AttributeError: 'module' object has no attribute 'mkdirs'
I also want to know if my idea of saving it in the directory will work, which I haven't been able to test because of the errors I've been getting in the above portion.
os.mkdirs() is not a method in os module.
if you are making only one direcory then use os.mkdir() and if there are multiple directories try using os.makedirs()
Check Documentation
You are looking for either:
os.mkdir
Or os.makedirs
https://docs.python.org/2/library/os.html
os.makedirs makes all the directories, so if I type in shell (and get nothing):
$ ls
$ python
>>> import os
>>> os.listdir(os.getcwd())
[]
>>> os.makedirs('alex/is/making/a/path')
>>> os.listdir(os.getcwd())
['alex']
It has made all the directories and subdirectories. os.mkdir would throw me an error, because there is no "alex/is/making/a" directory.

Creating a file in a non-existing folder using OpenCV in Python [duplicate]

This question already has answers here:
Python using open (w+) FileNotFoundError [duplicate]
(1 answer)
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 6 months ago.
i am trying to create an image file using opencv in python.
when i am creating it in same folder file is created
face_file_name = "te.jpg"
cv2.imwrite(face_file_name, image)
but when i am trying to create it in another folder like
face_file_name = "test\te.jpg"
cv2.imwrite(face_file_name, image)
file is not created. can someone explain the reasons??
i even tried giving absolute path.
i am using python2.7 in windows.
cv2.imwrite() will not write an image in another directory if the directory does not exist. You first need to create the directory before attempting to write to it:
import os
dirname = 'test'
os.mkdir(dirname)
From here, you can either write to the directory without changing your working directory:
cv2.imwrite(os.path.join(dirname, face_file_name), image)
Or change your working directory and omit the directory prefix, depending on your needs:
os.chdir(dirname)
cv2.imwrite(face_file_name, image)

What is the Python equivalent of Perl's FindBin? [duplicate]

This question already has answers here:
How do you properly determine the current script directory?
(16 answers)
Closed 5 years ago.
In Perl, the FindBin module is used to locate the directory of the original script. What's the canonical way to get this directory in Python?
Some of the options I've seen:
os.path.dirname(os.path.realpath(sys.argv[0]))
os.path.abspath(os.path.dirname(sys.argv[0]))
os.path.abspath(os.path.dirname(__file__))
You can try this:
import os
bindir = os.path.abspath(os.path.dirname(__file__))
That will give you the absolute path of the current file's directory.
I don't use Python very often so I do not know if there is package like FindBin but
import os
import sys
bindir = os.path.abspath(os.path.dirname(sys.argv[0]))
should work.
To update on the previous answers, with Python 3.4+, you can now do:
import pathlib
bindir = pathlib.Path(__file__).resolve().parent
Which will give you the same, except you'll get a Path object that is way more nice to work with.

Categories