shutil.rmtree does not remove directory - python-3.x

I'm struggling with one error for few hours now. I'm making a setup.exe for my program. Each time I install it I want old dirs and files to be removed and created again. The code I use for that is:
import os
import shutil
data_path = os.path.join(os.environ['HOMEDRIVE'], '\ProgramData', 'MyDir')
shutil.rmtree(data_path, ignore_errors=True)
os.makedirs(data_path)
When I run this I see an error <FileExists> You can not create file that already exists: 'C:\\ProgramData\\MyDir'

Related

How to import a module from parent directory within a subdirectory

I was working on a simple project, bike_rentals. I thought all was well until I began writing test files for the project.
I created a new directory and name it TestBikeRental and saved it within the BikeRentals directory, which contained the scripts for my project. I created the file init.py within the BikeRentals and TestBikeRentals directory to make them each be a package. Within the top directory is the script run_script.py that I use to run the modules\scripts contained in the package BikeRentals.
Directory structure
The problem comes up when I try to import the py script db_connection (underlined in yellow), within the Test_bike_rentals.py.
This is how tried to imported db_connection.
Importing db_connection
After numerous and numerous attempts, the errors that I kept receiving were these two:
from BikeRentals.BikeRentals.db_connection import Connect
ModuleNotFoundError: No module named 'BikeRentals'
from..db connection import Connect
ImportError: attempted relative import with no known parent package
To view the sourcecode in github repo:
https://github.com/Brownred/Python-and-SQL
I tried to import a module but got an error after numerous attempts. I was expecting no error when it comes to importing a module.

Where does python send files without a directory path?

I'm using Windows 10
Anyway I used os.rename and forgot to add a directory path to the beginning. Where did my files end up?
The file could be sent to the current working directory. To find the current working directory, use
import os
os.getcwd()
To find out where the file you are executing is located, use
import os
os.path.dirname(os.path.realpath(__file__))

VSCode raising error when I try to import an Image in Python

I am using Visual Studio Code Community Edition.
I am using code like below and running it:
from tkinter import *
tk = Tk()
img = PhotoImage(pathtoimage)
Button(tk, image=img).pack()
tk.mainloop()
And when I try to run this, I get this error:
_tkinter.TclError: couldn't open "Resources/ytbanner.png": no such file or directory
I have quadruple-checked that this exists. I have the script being run in the directory where Resources is and this is happening.
Here's the filetree:
Path to my desktop
Projectname
Script I'm using
Resources
PNG image I want to use
Is this some sort of VSCode bug or is it something with the directories?
I'm only 11, so please don't be toxic
This is the normal behavior of the VS Code python extension. It automatically cd into workspace root. So you have to define the path from the workspace root to the file. while this method works on VS Code, this code will break on other editors because they don't cwd into the workspace folder. And also if you open the script from VS Code but this time with an in a different workspace (maybe previous workspace folder's parent or something) it would throw an error. So the solution to this would be something like this:
import os
import sys
if sys.argv:
filepath = sys.argv[0]
folder, filename = os.path.split(filepath)
os.chdir(folder) # now your working dir is the parent folder of the script
# and your code
If your code didn't run on terminal, if statement will return False thus the indented block wouldn't work. However, usually when code isn't running on terminal cwd is the parent folder of the file as we want.

How to extract a zip file using python 3

How to extract a zip file using python when zip file present in different directory where script file present.
I try this ,but i got error because source path is not accepted ,try to solve me this problem.
from zipfile import ZipFile
def func(source, target):
with ZipFile('source', 'target'):
ZipFile.Extractall('target')
Use this code. To move through directories you could either hard code the directory where your script is present or you could toggle through the directories using simple commands such as "../" to move out of the given directory or "/" to move inside a folder in the directory. For example - "../script.py" or "/folder/script.py". Similarly you can use this to find your .zip file.
import zipfile
with zipfile.ZipFile("file.zip","r") as zip_ref:
zip_ref.extractall("targetdir")
For just unpacking, shutil should suffice:
import shutil
shutil.unpack_archive('path-to-zipfile')
You'll have to check for source path of the zip file which is relative to your current working directory. To know your current working directory you can try
import os
print(os.getcwd())
zip - Unzipping files in python
relative-paths-in-python

No module named xxxx. How to import relative path?

I have created a simplified version as to focus solely on getting the relative path to work. This is my file structure:
|
-project
|-package1
| |--page
| |-__init__
|
|-package2
|-test
|-__init__
I am trying to import page into test. However, I get the error that package1 is not a module. Below I have typed all that are in my code. Very simple. I am just trying to import page into test. Is there anything I am missing (file or page set up) that is preventing me from importing?
page.py
one='half'
two='ling'
tests.py
import os
import sys
three = (one+two)
print(three)
Have you tried "from package1 import page" into your test.py? Or "from package1.page import page"?
UPDATE
When import something, Python Interpreter search in the following places:
Built-ins
Current Directory
$PYTHONPATH, environment variable
some other directory related to the installation
The last three make up to be sys.path.
In your case, to import package1 into some script in package2, there's 2 ways:
Add project path into PYTHONPATH.
Dynamically append project path into sys.path
I guess you would appreciate the latter solution, just add
import sys
sys.path.append('..')
in front of everything and it will work.
Plus: It's kind of inconvenient to use the module not inside the current directory though. I've seen only a few actual python project, and What I've seen is some of them use a single main.py in the project root to run the whole project, including test-cases. Maybe this structure is more recommended.
Hope it helps~
Original Answer:
This dir structure works fine on my computer with:
import package.page as page
page.foo() # a function in page
Could I have a guess: your current working directory may be not under your project directory.
To check, test about this:
import os
print(os.getcwd())
If the output is not your current directory, that's my case. I used to mess with this before.
To avoid this, you can:
cd to your directory before running Python
run os.chdir(...) in your code, which is to change your working directory.
If not this case, please provide more information.

Resources