I 'm trying to open a directory dialog with a default directory which is written into an .ini file.
The .ini file looks like this :
defaultWorkingDirectory = "%%USERPROFILE%%\Documents\CAD\Working_Directory"
And I wrote a function in order to open the directory dialog :
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
from os.path import expanduser
import configparser
import itertools
import re
self.home = expanduser("~")
self.defaultPath = self.home + "\Documents\OptCAD\Working_Directory"
def openDirectoryDialog(self):
cfg = configparser.ConfigParser()
cfg.read_file(itertools.chain(['[global]'], open('C:\\Program Files (x86)\\CAD\\config.ini')))
print(cfg.items('global')) # It returns : [('defaultworkingdirectory', '"%USERPROFILE%\\Documents\\OptCAD\\Working_Directory"')]
cfgList = cfg.items('global')
wDirTuple = cfgList[(0)]
_, workingDir = wDirTuple
print(workingDir) # It returns : "%USERPROFILE%\Documents\OptCAD\Working_Directory"
self.directoryName = str(QFileDialog.getExistingDirectory(self, "Select Working Directory", workingDir, QFileDialog.ShowDirsOnly))
Then when I open the directory dialog the default directory is not the good directory.
You can always get the user profile path using expanduser, what is the need of %USERPROFILE%? You can store relative path in your config file in your case Documents\OptCAD\Working_Directory and then read it in the same way as you did in a variable say, relativeWorkingDir. Finally join it with the user profile like this.
workingDir = os.path.join(os.path.expanduser('~'), relativeWorkingDir)
I assume what you're trying to do is read values from the config file of program that you don't control.
The %USERPROFILE% syntax is windows-specific way of referring to environment variables. It won't be automatically exapnded by either Python or Qt, so you have to do it yourself:
import os
userprofile = os.environ.get('USERPROFILE')
workingdir = cfg.get('global', 'defaultworkingdirectory', fallback=None)
if workingdir and userprofile:
workingdir = workingdir.replace('%USERPROFILE%', userprofile)
else:
workingdir = os.exanduser('~\Documents\OptCAD\Working_Directory')
Related
I have a custom PyPi package. It is installed under Pyhon\Python38\Lib\site-packages\myCustomPackage.
In the __init__ code for myCustomPackage, I perform a few different directory operations, which failed to find the correct files and directories which reside in the Pyhon\Python38\Lib\site-packages\myCustomPackage folder.
I looked at the output of os.getcwd() and it showed the cwd to be C:\Users\TestUser, which is the root Windows user folder.
I would like the root folder to be the myCustomPackage folder.
For example, the file \myCustomPackage\__init__.py would contain
import os
class myCustomPackage():
def __init__(self):
print(os.getcwd())
If I run:
from myCustomPackage import myCustomPackage
theInstance = myCustomPackage()
The output is:
C:\Users\TestUser
How can I change that to be C:\Users\TestUser\AppData\Local\Programs\Python\Python38\Lib\site-packages\myCustomPackage?
Note : I would want it to be dynamic. No hard coding, in case the python version changes or the Windows user changes.
To get the directory path of the current module, you can use the built-in __file__.
To set the cwd to the module directory, use:
import os
import sys
from pathlib import Path
class myCustomPackage():
def __init__(self):
module_directory = Path(__file__).parent
os.chdir(module_directory)
print(os.getcwd())
My solution was the following function:
import site
import os
import traceback
def changeCWD(self):
try:
sitePackages = site.getsitepackages()
site_packages_dir = sitePackages[1]
top_module_dir = site_packages_dir + os.path.sep + "myCustomPackage"
os.chdir(top_module_dir)
return True
except:
self.myLogger.error("An error occurred in changeCWD")
tb = traceback.format_exc()
self.myLogger.exception(tb)
return False
I want to ask is it possible to make a rules for file managing program. For instance, if i want to move certain file in Image folder to move only .png and .img files. How i should declare rule in the configuration file that program would understand? If you would need I would my code gladly upload it. Which libraries i would need to use or give certain examples? Thank you in advance!
from tkinter import *
from tkinter import filedialog
import easygui
import shutil
import os
from tkinter import filedialog
from tkinter import messagebox as mb
from pathlib import Path
import logging
from datetime import date
import configparser
import configdot
def open_window():
read=easygui.fileopenbox()
return read
#logging config
if Path('app.log').is_file():
print ("Log file already exist")
else:
logging.basicConfig(filename='app.log', filemode="w", format='%(name)s - %(levelname)s - %(message)s ')
print ("Log file doesn't exist, so new one was created")
LOG_for="%(asctime)s, %(message)s"
logger=logging.getLogger()
logger.setLevel(logging.DEBUG)
# move file function
def move_file():
filename = filedialog.askopenfilename(initialdir = config.select.dir,
title = config.select.ttl,
filetypes = config.select.ft)
destination =filedialog.askdirectory()
dest = os.path.join(destination,filename)
if(source==dest):
mb.showinfo('confirmation', "Source and destination are the same, therefore file will be moved to Home catalog")
newdestination = Path("/home/adminas")
shutil.move(source, newdestination)
logging.shutdown()
logging.basicConfig(filename='app.log', filemode="a", format=LOG_for)
logging.info('File *' + filename + '* was moved to new destination: ' + newdestination)
else:
shutil.move(source, destination)
mb.showinfo('confirmation', "File Moved !")
#current_time()
logging.basicConfig(filename='app.log', filemode="a", format=LOG_for)
logging.info('File *' + filename + '* was moved to new destination: ' + destination)
# Create the root window
window = Tk()
It sounds like you want to move only files of a specific type (e.g. .png or .img). You can do this based on the file name itself using endswith:
if source.endswith('.png'):
shutil.move(source, newdestination)
You can see an example in this answer Converting images to csv file in python where the function walks through a directory and creates a list of files that all share the same file extension.
Note that this code only checks the file extension, not the actual file itself.
Now, say you only want to apply this rule to a folder called "Images", then you can still use string manipulation. You might use contains:
if source.contains("Images"):
# do something
Alternatively, if you know your file path might contain the word "Images" more than once, you can use os.path.split(path) to split the path into "path" and "file", and then again on the resulting head to split it into "path" and last folder. Compare the resulting tail to Images:
h, t = os.path.split(source)
h2, t2 = os.path.split(h)
if t2.contains("Images"):
#do something
There are other ways to do this using the os.path functions and you will want to investigate these.
I have the following code:
import datetime as date
import os
import pdfkit
import getpass #Gets me current username
username = getpass.getuser()
path = f"/home/{username}/Data"
relative_path = os.path.relpath(path, os.getcwd())
destination = os.path.join(relative_path, 'data.pdf')
pdfkit.from_url('www.google.com', f'{destination}/data.pdf')
I want the pdf to be saved in windows equivalent of /home/[username]/datafolder. I don't really need to use use linux or mac but for academic reasons i have decided to use the relative path method.
This code makes sense to me but for some reason it is not the directory i want it to be because when i specify the path this way the pdf generator, generates an error.
Error: Unable to write to destination
Exit with code 1, due to unknown error.
I know the error is in the last line of code where i have specified '/relative_path/data.pdf'. Could you please advise how i can resolve this issue?
Update 1:
As suggested by #Matthias I have updated the code but I am still getting the same error
Update 2:
I tried:
from pathlib import Path
destination = Path.home()
try:
os.mkdir(destination\Data)
except OSError as error:
print(error)
But it is still not pointing to the directory Data
Update 3
I know i am getting closer:
import pdfkit
import datetime as date
import calendar
import os.path
import getpass
username = getpass.getuser()
path = f"/home/{username}/Data"
os.makedirs(relative_path, exist_ok=True)
#start = os.getcwd()
relative_path = os.path.relpath(path, os.getcwd())
destination = os.path.join(relative_path, 'data.pdf')
pdfkit.from_url('www.google.com', f'{relative_path}/data.pdf')
At this point the code is executes but the folder Data was not created not am i able to locate data.pdf. I did get sucessful run though:
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
Any ideas on how i can get this working correctly? The code does not produce the folder or the file?
Just check by putting
relative_path line before os.makedirs
As below
import pdfkit
import datetime as date
import calendar
import os.path
import getpass
username = getpass.getuser()
#path = os.path.join("home","{username}","Data")
# in case of window you will need to add drive "c:" or "d:" before os.path.sep
path = os.path.join(,"home",username,"Data")
relative_path = os.path.relpath(path, os.getcwd())
os.makedirs(relative_path, exist_ok=True)
#start = os.getcwd()
destination = os.path.join(relative_path, 'data.pdf')
pdfkit.from_url('www.google.com', f'{relative_path}/data.pdf')
Maybe you could change your last line to:
pdfkit.from_url('www.google.com', f'{relative_path}/data.pdf')
in order to get it to save to the home directory.
Perhaps the issue is that the directory doesn't exist. You could use os.makedirs to create the directory, using the exist_ok=True flag in case the directory already exists. Like so:
import datetime as date
import os
import pdfkit
import getpass #Gets me current username
username = getpass.getuser()
path = f"/home/{username}/Data"
os.makedirs(path, exist_ok=True)
pdfkit.from_url('www.google.com', f'{path}/data.pdf')
You can use os.environ. Run this little script on your machine:
import os
for key, value in os.environ.items():
print(key, '-->', value)
and see for yourself what you need exactly. It's portable as well.
Let's say you want to get the path of the user's home directory. You could get it from os.environ['HOME'] and then create the path to the target directory using os.path.join(os.environ['HOME'], 'target_directory_name').
You won't be able to create files in a directory if you don't have the required permissions, though.
User folders in windows are stored in "/Users/{username}/*". I don't know if you are trying to make this compatible for multiple OSs but if you just want to make this run on windows try:
path = f"/Users/{username}/Data"
start = f"/Users/{username}"
Hope it works.:)
Edit:
To get the home directory of a user regardless of OS you could use
from pathlib import Path
home = str(Path.home())
sorry for the late edit.
My script is trying to read my utils from a different folder. I keep getting Import Error. PFB my script :
import sys
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname+"/../../dags/golden/")
dname = os.path.dirname(abspath)
sys.path.append(dname)
import utils
semantics_config = utils.get_config()
And my folder structure is as follows :
/home/scripts/golden/script.py
/home/dags/golden/utils.py
Output is :
Traceback (most recent call last):
File "check.py", line 22, in
import utils
ImportError: No module named utils
Any pointers will be greatly helpful!
Try this
import sys
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname+"/../../dags/golden/")
dname = os.getcwd()
sys.path.append(dname)
import utils
semantics_config = utils.get_config()
You are again assigning "dname" as old path.
So use os.getcwd()
or
import sys
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
sys.path.append(dname+"/../../dags/golden/")
import utils
semantics_config = utils.get_config()
You made a mistake in your script.
os.chdir(dname+"/../../dags/golden/"), only changes your current working directory, but not change the value of variable "abspath"
So the value of "dname" keep the same before and after your "os.chdir"
just do sys.path.append(dname+"/../../dags/golden/"), you will get what you want.
BTW, python is very easy to locating the problem and learn. Maybe, You just need to add a print before you using a variable. And, don't forge to remove those print before you release your scripts.
How would I edit the path of a file I created with file.open in python? For example, with my code:
import sys
import os
import os.path
GENPASS = ["g","q"]
FILENAME = "Test.txt"
ACC = "Test"
FILE = open(FILENAME,'a')
FILE.write(ACC)
FILE.write(','.join(GENPASS)+"/n")
How would I change the path of "FILE"
To change the path of FILE you will have to set it up in this declaration:
e.g.
FILENAME = "/mypath/Test.txt"