How can I safely create a nested directory?
On Python ≥ 3.5, use pathlib.Path.mkdir
:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:
Try os.path.exists
, and consider os.makedirs
for the creation.
import os
if not os.path.exists(directory):
os.makedirs(directory)
As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists
and the os.makedirs
calls, the os.makedirs
will fail with an OSError
. Unfortunately, blanket-catching OSError
and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.
One option would be to trap the OSError
and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):
import os, errno
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
Alternatively, there could be a second os.path.exists
, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.
Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.
Modern versions of Python improve this code quite a bit, both by exposing FileExistsError
(in 3.3+)...
try:
os.makedirs("path/to/directory")
except FileExistsError:
# directory already exists
pass
...and by allowing a keyword argument to os.makedirs
called exist_ok
(in 3.2+).
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
How can create a nested directory?
Try this one for directory:
os.path.isdir(file_path)
To check if a file exist, try this:
os.path.isfile(file_path)
create nested folders in current directory in R?
This should do it:
cidr <- getwd()
mkfldr <- "test1/project/code/example"
dir.create(file.path(cidr, mkfldr), recursive = TRUE)
Create file along with nested directory in single command line
If I understand correctly and you simply want to be able to issue command foo/bar/baz/myfile.txt
(or something similar) and have the directories foo/bar/baz
created and a new file myfile.txt
created and opened in nano
all by that one command, then a short script is all you need, e.g.
Make it executable e.g. mv nanoopen.sh scriptname; chmod 0755 scriptname
, then just call ./scriptname
foo/bar/baz/file.txt
. If you put it in your path, you can skip the ./ too.
The easy way to put it in your path is to create a symlink to it in /usr/local/bin
which is generally in the default path.
So you could (sometime supersure is needed) ln -s /path/to/nanoopen.sh /usr/local/bin/scriptname
. Echo $PATH to confirm /usr/local/bin is in your path, then just use it like any program, scriptname arguments.
Or in some distros you can simply add it to /bin
folder with root access.
#!/bin/bash
[ -z "$1" ] && { ## validate one argument given
printf "error: insufficient input\nusage: %s filename\n" "${0##*/}"
exit 1
}
[ "$1" != "${1##*/}" ] && mkdir -p "${1%/*}" ## if it has directories, create
touch "$1" ## create the file
exec nano "$1" ## open in nano
Example Use/Output
$ bash nanoopen.sh foo/bar/baz/main.c
$ tree foo/
foo/
└── bar
└── baz
└── main.c
$ cat foo/bar/baz/main.c
My new source!
Create nested dictionary from directory
instead of using the assignment operator here:
dict[key] = {x[:-4]: {'path': f'database/{x}'}}
call the update
method on the dictionary:
dict[key].update({x[:-4]:{'path': f'database/{x}'}})
Check if Directory Exists, create nested directory
@Barmar Thank you for your help and patience!
I found were the problem lies.
def gen_subregion(srcimg, seg_image, trainimagefile, trainMaskfile, expandslice=5):
# 5 get the roi range of mask,and expand number slices before and after,and get expand range roi image
# for kinery
startpostion, endpostion = getRangImageDepth(seg_image)
if startpostion == endpostion:
return
imagez = np.shape(seg_image)[0]
startpostion = startpostion - expandslice
endpostion = endpostion + expandslice
if startpostion < 0:
startpostion = 0
if endpostion > imagez:
endpostion = imagez
src_kineryimg = srcimg[startpostion:endpostion, :, :]
seg_kineryimage = seg_image[startpostion:endpostion, :, :]
# 6 write src, liver mask and tumor mask image
for z in range(seg_kineryimage.shape[0]):
src_kineryimg = np.clip(src_kineryimg, 0, 255).astype('uint8')
cv2.imwrite(trainimagefile + "//" + str(z) + ".bmp", src_kineryimg[z])
cv2.imwrite(trainMaskfile + "//" + str(z) + ".bmp", seg_kineryimage[z])
I had to change \\
to //
.
Related Topics
Why Can't I Iterate Twice Over the Same Data
Converting Unix Timestamp String to Readable Date
How Do Python'S Any and All Functions Work
How to Play Wav File in Python
How to Use a Variable Inside a Regular Expression
How to Sort a List of Strings Numerically
How to Convert an Rgb Image into Grayscale in Python
Sorting Arrays in Numpy by Column
Why Is "Except: Pass" a Bad Programming Practice
How to Play an Mp3 With Pygame
Return, Return None, and No Return At All
Equivalent of Shell 'Cd' Command to Change the Working Directory
How to Find the Location of My Python Site-Packages Directory
How Does Tuple Comparison Work in Python
Do Regular Expressions from the Re Module Support Word Boundaries (\B)