简体   繁体   中英

I want to create directory and save image file but its name already exist its should have numbers indicating

I want to create directory from input:"imgdir" in same name but its name already exist it should have numbers indicating that it is the second directory like imgdir(2)/ and if input "imgdir" again it will make directory name imgdir(3)/

existing directory

dir-----|
        |-imgdir/


after make directory name "imgdir"

dir-----|
        |-imgdir/
        |-imgdir(2)/

after make directory name "imgdir" again

dir-----|
        |-imgdir/
        |-imgdir(2)/
        |-imgdir(3)/  

and I want to save image and its name already exist it should have numbers indicating like making directory

existing image

dir-----|
        |-imgdir|-----/pic.jpg

after save(pic.jpg)

dir-----|
        |-imgdir|-------/pic.jpg
                        /pic(2).jpg    


after save(pic.jpg) again

dir-----|
        |-imgdir|-------/pic.jpg
                        /pic(2).jpg
                        /pic(3).jpg

Using the path module , you'd have to check if the existing path exists.

So checking if the image exists, you'd check


# Check if the base path exists
save_path = "pic.jpg"

# Check if it exists and otherwise modify path
i = 2
while path.exists(save_path):
    save_path + "(" + i + ")"
    i += 1

# Write your file here

The same process you can use for the folders.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM