I want to check if there exist a folder in the current folder my code is in, how can this be done?
What I mean is, we have folder called code_folder, which has the python code, i want to check in this python code if in this code_folder we have another folder called folder_1, if is it exists we can store something in it, if not we creat the folder and store something in it.
try this code
import os
path = "code_folder"
# Check whether the defined path exists or not
if not os.path.exists(path):
# Create a new directory
os.makedirs(path)
print("The new directory is created!")
else:
pass
You can use pathlib for this.
if pathlib.Path("path/to/code_folder/folder_1").isdir():
print("the directory exists")
But really, you don't need to check anything, you can just use the exists_ok argument of Path.mkdir, so just:
pathlib.Path("path/to/code_folder/foler_1").mkdir(exists_ok=True)
Related
I am quite new to python so I need some help. I would like to create a code that checks if a folder with a given name is created, if not, it creates it, if it exists, goes to it and in it checks if there is another folder with a given name, if not, it creates it. In my code I don't know how to go to folder that already exist or has just been created and repeat IF.
import os
MYDIR = ("test")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
print("created folder : ", MYDIR)
else:
print(MYDIR, "folder already exists.")
If you want to create a folder inside a second folder or check the existence of them you can use builtin os library:
import os
PATH = 'folder_1/folder_2'
if not os.path.exists(PATH):
os.makedirs(PATH)
os.makedirs() create all folders in the PATH if they does not exist.
os has an inbuilt method for this, you can simply do: os.makedirs("dir", exist_ok=True). This will basically create a folder if it does not exist and do nothing if the folder already exists.
Documentation: https://docs.python.org/3/library/os.html#os.makedirs
#!/usr/bin/python
import os
directory0="directory0"
## If folder doesn't exists, create it ##
if not os.path.isdir(directory0):
os.mkdir(directory0)
You can use os import or pathlib to manage your path (example: to know if your path is a dir, if exist ...)
The os import have OS dependent features, so I recommend to use pathlib.
If you check on google you will find lot of example like:
https://www.guru99.com/python-check-if-file-exists.html
https://www.geeksforgeeks.org/create-a-directory-in-python/
Is there a way to change your directory to the most recently generated directory? I am creating a new directory every 12 hours and want to iteratively loop through the most recent x amount of directories.
Something similar to this but for a directory.
How to get the latest file in a folder using python
The following should basically work.
import os
parent_dir = "." # or whatever
paths = [os.path.join(parent_dir, name) for name in os.listdir(parent_dir)]
dirs = [path for path in paths if os.path.isdir(path)]
dirs.sort(key=lambda d: os.stat(d).st_mtime)
os.chdir(dirs[-1])
Note that this will change to the directory with the most recent modification time. This might not be the most recently created directory, if a pre-existing directory was since modified (by creating or deleting something inside it); the information about when a directory is created is not something that is stored anywhere -- unless of course you use a directory naming that reflects the creation time, in which case you could sort based on the name rather than the modification time.
I haven't bothered here to guard against race conditions with something creating/deleting a directory during the short time that this takes to run (which could cause it to raise an exception). To be honest, this is sufficiently unlikely, that if you want to deal with this possibility, it would be sufficient to do:
while True:
try:
#all the above commands
break
except OSError:
pass
I use the very usefull OS library for IT automation.
Bellow the code to create a folder / move into the folder / create a file
import os
# create a directory
os.mkdir("directory")
# get the path of the directory
path = os.path.abspath("directory")
print(f"path after creating the directory: {path}")
# change current directory
os.chdir("directory")
path = os.path.abspath("directory")
print(f"path after changing current directory: {path}")
# create a file
with open("hello.py", "w"):
pass
oupput:
path after creating the directory: P:\Code\Python\directory
path after changing current directory: P:\Code\Python\directory\directory
I don't understand something:
Why the path of the directory file is changing?
I don't have any directory into \directory
Thanks for your answers
If you read the documentation of the [abspath][1] function, you would understand why the extra directory is coming.
Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).
Basically, os.path.abspath('directory') is giving you "the absolute path of something named 'directory' inside the current directory (which also happens to be called 'directory') would be"
The absolute path you're seeing is for something inside the directory you just created, something that doesn't yet exist. The absolute path of the directory you created is stil unchanged, you can check that with:
os.path.abspath('.') # . -> current directory, is the one you created
os.path.abspath translates a the name of a file specified relative to your current working directory, however, the file does not necessarily exist.
So the first call of abpath:
# get the path of the directory
path = os.path.abspath("directory")
print(f"path after creating the directory: {path}")
does nothing more than putting your current working directory in front of the string "directory", you can easily do this by yourself:
os.getcwd() + '/' + "directory"
If you change your working directory with os.chdir("directory") the os.getcwd() returns P:\Code\Python\directory, and appends the second "\directory" to the path. Here you see, that the file does not have to exist.
I've written a script that basically creates two new folders when it's run the first time, if the folders don't already exist.
import os
try:
os.makedirs('results/graphs')
except OSError:
pass
And everytime the script is run, the graphs are produced in the results/graphs folder.
But I noticed recently that if the script is run from another directory, (eg. script is in home/user/script/ but I run it from: home/user/programs/), the new folders are created in home/user/programs/.
My goal is ultimately that the folders are created only in the script folder and all eventual graphs that are produced will thus be destined to home/user/script/results/graphs.
Is there someway to achieve this using python?
I'm using Debian 8 and python 2.7.13. The graphs are produced using matplotlib.
It's a solution for me, check it (I tried it on windows):
import os
d = os.path.dirname(__file__) # directory of script
p = r'{}/results/graphs'.format(d) # path to be created
try:
os.makedirs(p)
except OSError:
pass
In your script results/graphs refers to the results folder within whatever folder you ran the script from. If you always want the folders to be created in /home/user/script/results/graphs use ~/script/results/graphs in your script instead. Alternatively you could hard code the whole path, /home/user/script/results/graphs.
There is another way, apart from hard coding which is mentioned earlier. You can use __file__ to extract the path of the file where the script is present. And then you can use it to append as parent path to results/graphs
All you have to do is to define the path where your script is. This can be done within the code as:
path = 'home/user/script/'
or by getting the input from the user using a filedialog box.
Then you can use the path variable to make the directories.
os.makedirs(path + 'results/graphs')
##creating folder
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
dirctry = os.path.dirname(file_path)
toolSharePath = os.path.abspath(dirctry)
final_directory = os.path.join(toolSharePath, r'new_folder')
if not os.path.exists(final_directory):
os.makedirs(final_directory,exist_ok=True)
A very basic question, I have a module that creates directories on the fly, however, sometimes I want to put more than one file in a dir. If this happens, python rises an exception and says that the dir is already created, how can I avoid this and check if the dir is already created or not?
The save module looks something like this:
def createdirs(realiz):
# Create all the necessary directories
path = "./doubDifferences_probandamp_realiz%d/"%realiz
os.mkdir(path,0755)
directory = os.path.split(path)[0]
return directory
On the main program, I have this:
for realiz in range(1,1000):
for i in range(dim):
for j in range(i+1,i+4):
...
dirspaths = mod_savefile.createdirs(realiz)
You could go for a try except:
try:
os.mkdir(path,0755)
except OSError:
pass
“Easier to ask forgiveness than permission !”
Also this method is more safe that testing the directory before doing mkdir. Indeed, it is fairly possible that between the two os call implied by ispath and mkdir the directory may have been created or destroyed by another thread.
This should cover you. Just test if it is a directory before you try to create it.
if not os.path.isdir(path)
os.mkdir(path,0755)
You have several ways. Either use os.path.isdir function:
import os.path
def createdirs(realiz):
# Create all the necessary directories
path = "./doubDifferences_probandamp_realiz%d/"%realiz
if not os.path.isdir(path): # if not exists
os.mkdir(path,0755) # create it
directory = os.path.split(path)[0]
return directory
Or handle the exception.