How can I make folder in another folder? - Python - python

I want to make subfolder in another folder. I can make main folder but I don't know how to make other folder in this.
import os
fol = os.makedirs('2020')

Using makedirs you can do at once
os.makedirs('2020/subfolder/subsubfolder')
and it should create 2020, next 2020/subfolder, and next 2020/subfolder/subsubfolder
If you already created folder 2020 then you can also use path with 2020/ at the beginning to create subfolder
os.makedirs('2020/subfolder')
or you can change folder and then create subfolder without using 2020/
os.chdir('2020')
os.makedirs('subfolder')
BTW: probably since Python 3.6 or 3.7 you can use exist_ok=True to skip creating if folder already exist.
os.makedirs('2020/subfolder', exist_ok=True)
Without exist_ok=True it would raise error if folder already exist. And you would need this:
if not os.path.exists('2020/subfolder'):
os.makedirs('2020/subfolder')

Related

Creating ZIP folder with shutil - Python

I'm trying to use shutil.make_archive but it's duplicating the folder name. Let me explain better:
My folder R360 to be ziped is located at: C:\Users\PycharmProjects\Project\media\SAE\R360\
What I am trying to do is: create a zip folder with this same name. So in the SAE directory, it should be the regular folder R360 and then R360.zip.
My code:
folder = C:\Users\PycharmProjects\Project\media\SAE\R360
mediaFolder = C:\Users\PycharmProjects\Project\media\
shutil.make_archive(f'{folder}', 'zip', f"{mediaFolder}SAE/", f"{folder.split('/')[-1]}/")
The R360.zip is being created normally but the problem is that the zip folder is like this:
C:\Users\PycharmProjects\Project\media\SAE\R360.zip\R360\...
What I really wanted:
C:\Users\PycharmProjects\Project\media\SAE\R360.zip\...
It shouldn't be that R360 inside the zip folder.
I'd like to post my own question for other who are facing the same issue!
folder = C:\Users\PycharmProjects\Project\media\SAE\R360
mediaFolder = C:\Users\PycharmProjects\Project\media\
shutil.make_archive(f'{folder}/', 'zip', f"{mediaFolder}SAE/{folder.split('/')[-1]}")
This will create the zip file, without duplicating the folder itself inside the zip!

Navigating directories

After getting the path to the current working directory using:
cwd = os.getcwd()
How would one go up one folder: C:/project/analysis/ to C:/project/ and enter a folder called data (C:/project/data/)?
In general it a bad idea to 'enter' a directory (ie change the current directory), unless that is explicity part of the behaviour of the program.
In general to open a file in one directory 'over from where you are you can do .. to navigate up one level.
In your case you can open a file using the path ../data/<filename> - in other words use relative file names.
If you really need to change the current working directory you can use os.chdir() but remember this could well have side effects - for example if you import modules from your local directory then using os.chdir() will probably impact that import.
As per Python documentation, you could try this:
os.chdir("../data")

How to access a file a path level below from a subfolder

Let's say I have a file called credentials.json in my current directory, an environment variable MY_CREDENTIALS=credentials.json and a script main.py that uses this environment variable via os.getenv('MY_CREDENTIALS').
Now suppose I create a subfolder and put something there like this: /subfolder/my_other_script.py.
If I print os.getenv('MY_CREDENTIALS') then I get indeed credentials.json but I can't use this file as it is in my root directory (not in /subfolder). So, how can I use this file although it is in the root directory? The only thing that works for me is to make a copy of credentials.json in /subfolder, but then I would have multiple copies of this file and I don't want that.
Thanks for your response!
Something like this could work:
from pathlib import Path
import os
FILENAME = os.getenv('MY_CREDENTIALS')
filePath = Path(FILENAME)
if filePath.exists() and filePath.is_file():
print("Success: File exists")
print(filePath.read_text())
else:
print("Error: File does not exist. Getting file from level below.")
print((filePath.absolute().parent.parent / filePath.name).read_text())
Basically, you check whether your file exists in the current folder. This will be the case, if your script is in your root folder. If it is not, you assume that you are in a subfolder. So you try to get the file from one level below (your root).
It's not totally production ready, but for the specific case you mentioned it should work. In production you should think about cases where you might have nested subfolder or your file is missing for good.
You can create symbolic link
os.symlink('<root>', '<subfolder>')
https://docs.python.org/3/library/os.html#os.symlink

Python name of latest folder created in a directory

I am new to python and have to play with directories.
Can someone help me with it?
I have to know a path with newly created folder. A new temp folder is generated by my code in which some files are copied. I have to know the path of this folder , but folder name is random , so I want to fetch the folder name of latest created folder.
What shall i do?
You can do something like this:
import os
directory = '.' # current dir
folders = os.walk(directory).next()[1]
creation_times = [(folder, os.path.getctime(folder)) for folder in folders]
creation_times.sort(key=lambda x: x[1]) # sort by creation time
Then you can pick the last element of this list:
most_recent = creation_times[-1][0]
Its a bad practice to fetch the latest folder created because some other application may create a folder right before you fetch the latest folder, but if you really want to try it out the code what elyase has demonstrated is fine.

How to create new folder? [duplicate]

This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Closed 8 years ago.
I want to put output information of my program to a folder. if given folder does not exist, then the program should create a new folder with folder name as given in the program. Is this possible? If yes, please let me know how.
Suppose I have given folder path like "C:\Program Files\alex" and alex folder doesn't exist then program should create alex folder and should put output information in the alex folder.
You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:
newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
os.makedirs(newpath)
If you're trying to make an installer: Windows Installer does a lot of work for you.
Have you tried os.mkdir?
You might also try this little code snippet:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
makedirs creates multiple levels of directories, if needed.
You probably want os.makedirs as it will create intermediate directories as well, if needed.
import os
#dir is not keyword
def makemydir(whatever):
try:
os.makedirs(whatever)
except OSError:
pass
# let exception propagate if we just can't
# cd into the specified directory
os.chdir(whatever)

Categories