Create folder and subfolder with django app - python

Maybe this is to trivial question, but please assist me. How can I create folder and subfolder in it with django python. When I google I just get some information about folder structure, but it is not what I am looking for. Please share some code examples if it is possible
Many thanks.

why don't look up for how to create folders and subfolders with python using the subprocess or os ?
the ok command (linux and macos) is mkdir -p /path/you/want

You don't need much more:
import os
# creating subfolder in the directory of launched script
os.makedirs("subfolder", exist_ok=True)
# constructing full absolute path to project_folder
ROOT_FOLDER = os.path.abspath(__file__)
print(ROOT_FOLDER)
# joining root_folder and subfolder in order to create\work with files in nested folders
subfolder_abs_path = os.path.join(ROOT_FOLDER, 'subfolder')
print(subfolder_abs_path)

Related

How can I make python download file to current directory of main.py?

I have a project on Gitlab that should download files to its current directory (regardless of user OS being Mac/Windows) when the user downloads the repo and uses it on locals. Also, I will read the same file again further in the program.
Can anyone suggest to me what directory name should I pass in the python variable to achieve this?
Thank you
If you want to download to the same folder as your python file, you can do
from pathlib import Path
dir_to_download_to = Path(__file__).parent
If you want to download to the same folder as the user is in, then
import os
dir_to_download_to = os.getcwd()

How can I run a python file that uses other folders with files, without using the computer's path?

My goal is to run a python file that uses files from a folder in the same folder as the python file, but regardless of the computer's path.
The situation I have now is that I have to define paths inside my code like: C:/Users/path/to/files/etc.
The ideal situation would be if I could create a main folder (preferably a zip folder) with the python file in it, and also the necessary folders with files that the python file is using. That way I could sent the main folder to anyone and they should be able to run the python file.
I am also using the os.listdir(C:/path/to/folder) function from the os library to import a whole folder, but this also works with the computer's path. So another alternative is needed.
Does anyone know how I could do this or at least something close to this?
You can use this to get the directory in which the current Python file is using abspath and dirname:
this_dir = os.path.abspath(os.path.dirname(__file__))
And then you can construct your relative paths in a OS independent way using join:
some_image = os.path.join(this_dir, 'images', 'myimage.png')
You can do something like this
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
If I understand correctly, you want to use python script in another file which is located in a sub folder in the same directory. Did I get it right?
If it is you can just import it as
from <folder name> import <file name>

How to share non-source files between Python projects?

Here's what I have:
Project A
----data_I_need.p
Project B
----use_data.py
If data_I_need.p were a source file (and in my path), I could easily import it into Project B. Does such method exist for non-source files?
Right now, I'm having to accomplish this with
with open('C:/......./data_I_need.p', 'rb') as data:
Project A is in my path (defined as 'Content Root' in PyCharm). I can imput source files from Project A.
To recap, the problem is that any Python file in PYTHONPATH can be imported, but resources (non-python files) cannot be loaded without an explicit path.
Project_A
----some_module.py
----data_I_need.p
Project_B
----use_data.py
Here is a solution. In Project B/use_data.py, include the following.
import os
import pathlib
import pickle
# full path to Project_B
here = os.path.dirname(__file__)
# path to folder *above* Project_B ---- joined to Project_A
PROJECT_A = os.path.join(*pathlib.Path(here).parts[:-1], 'Project A')
with open(os.path.join(PROJECT_A, 'data_i_need.p')) as resource:
var = pickle.load resource
This will work even if you're working in a shared drive (e.g., OneDrive) from two different operating systems.
Optionally, you could just set up a "shared_resources" folder and include a python script in that folder to access the resources, again working from os.path.dirname(__file__) then navigating the relative path.

Google App Engine - Multiple yaml files in one project share a lib

I want to create a multi-serivce app engine app, using the first diagram shown on this page.
https://cloud.google.com/appengine/docs/standard/python/configuration-files#an_example
I want to use third party libraries so I used have a lib folder under the root directory, one yaml under the root directory.
Then I want one microservice called predict. So I created a folder called predict under the root directory as well, then under this folder, I want to write py files using the packages in the lib as well.
What I'm doing is like this:
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
vendor.add(os.path.join(parentdir, 'lib'))
Which didn't work for me as the error says:
ValueError: virtualenv: cannot access /base/data/home/apps/f~project-name/lib: No such virtualenv or site directory
Obviously it didn't work for me, what's the right way to do this?
Update: Dan's solution worked for me! So when I'm deploying my microservice predict, I need to go inside predict directory and deploy it. I think that's why it can't find lib. By symlink the lib library using bash.
ln -s ../lib/ ./lib
I solved this problem.
The problem you're facing is that each service can only access files in its own service directory, which is the directory where its app.yaml file is located, they can't access the app's root directory.
My approach (all my services use standard environment):
created a lib dir in the top app dir and installed in it each package that I want shared across multiple services
each service has its own subdir in the app's dir and a lib directory in it where:
I installed libraries needed only by that service (if any)
I symlinked the needed shared libraries from the top lib dir
This is my app dir structure:
app_dir/
app_dir/dispatch.yaml
app_dir/cron.yaml
app_dir/index.yaml
app_dir/queue.yaml
app_dir/lib/
app_dir/lib/shared_lib_1/
app_dir/lib/shared_lib_2/
app_dir/lib/shared_lib_3/
app_dir/service1/
app_dir/service1/app.yaml
app_dir/service1/lib/shared_lib_1 -> ../../lib/shared_lib_1
app_dir/service1/lib/shared_lib_2 -> ../../lib/shared_lib_2
app_dir/service1/lib/service1_lib_1
app_dir/service2/
app_dir/service2/app.yaml
app_dir/service2/lib/shared_lib_2 -> ../../lib/shared_lib_2
app_dir/service2/lib/shared_lib_3 -> ../../lib/shared_lib_3
app_dir/service2/lib/service2_lib_1
No fumbling with the lib path is required, all I have in each service is
vendor.add('lib')
See related:
How do I access a vendored library from a module in Python Google App Engine?
Can a default service/module in a Google App Engine app be a sibling of a non-default one in terms of folder structure?
Check all the directories in the path and the final file to make sure they all exist first before code runs. If they don't, prepend the code you showed here with code to create them...

Is it possible to specify the previous directory python?

I am attempting to make a Python testing script module self-contained directory-wise for scalability and maintainability purposes.
I have done some research and haven't been able to find the answer i'm looking for. Basically, I would like to determine if there is a function in Python that can do something similar to cd - in shell.
I would generally like to avoid typing in full path-names, and have all the paths relative to a specified environment.
Example:
I have my main directory where my scripts are located python-scripts, I have folders for each testing environment demo, and a screenshot folder for each testing environment demo-screenshots.
If i wanted to save a screenshot to the screenshot with Python, while working in the demo directory, I would just send it to the directory below: demo-screenshots, using the path '/demo-screenshots/example.png'. The problem is that I don't understand how to move back a directory.
Thank you.
You're looking to change the working directory? The OS module in python has a lot of functions to help with this.
import os
os.chdir( path )
path being ".." to go up one directory. If you need to check where you are before/after a change of directory you can issue the getcwd() command:
mycwd = os.getcwd()
os.chdir("..")
#do stuff in parent directory
os.chdir(mycwd) # go back where you came from
path = os.path.dirname(__file__)
print(path)
will print the CWD of the file, say C:\Users\Test\Documents\CodeRevamp\Joke
path2 = os.path.dirname(path)
print(path2)
will print the Parent directory of of the file: C:\Users\Test\Documents\CodeRevamp

Categories