简体   繁体   中英

Create a directory with the date in python

I am trying to create a folder in python with the date time extension but every time i get the below error

  File "create_dir.py", line 7, in <module>
    os.mkdir("/home/xxx/" + time.strftime('%Y%m%d'))
OSError: [Errno 2] No such file or directory: '/home/xxx/20190322'

Here is my code:

#!/usr/lib/python
import os
import time
os.mkdir("/home/xxx/" + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))

I tried many solutions provided here in stack overflow , but all of them threw the same error.

You're probably missing to import datetime , Furthermore, you should use makedirs instead of mkdir , because makedirs() creates all the intermediate directories if they don't exist :

import os
import datetime
os.makedirs("C:\\Users\\PycharmProjects\\opencv-basics" + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))

OUTPUT (creates a folder with the path):

C:\Users\PycharmProjects\opencv-basics2019-03-22_14-49-26

os.mkdir will raise OSError if xxx or any intermediate path doesn't exist. Use os.makedirs when making arbitrary directories to ensure missing directories are also generated:

import os
import datetime

os.makedirs("/home/xxx/" + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))

Here's my suggested fix for your code:

#!/usr/lib/python
import os
import datetime
os.makedirs("/home/xxx/" + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))

And here's my explanation about what I did:

I cannot see the datetime import in your snippet but, since you mention no errors about it, I guess you just pasted an old version of the code.

Be sure that you are importing it.

About the main issue, since xxx folder doesn't exist, you should use the method makedirs instead of makedir:

os.makedirs(path[, mode])

This method also allows you to create the path if the path is not already there.

Here's official documentation

I will also copy the relevant part here on StackOverflow for simplicity:

os.makedirs(name, mode=0o777, exist_ok=False) Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.

The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed.

If exist_ok is False (the default), an OSError is raised if the target directory already exists.

Note makedirs() will become confused if the path elements to create include pardir (eg. “..” on UNIX systems). This function handles UNC paths correctly.

New in version 3.2: The exist_ok parameter.

Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082.

Changed in version 3.6: Accepts a path-like object.

Changed in version 3.7: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.

First of all, you need to import datetime , not time. Then, you either want to use os.makedirs which will create any intermediate directories which do not exist or you want to change the xxx which I assume is not your real home directory to what it actually is. Tested the above code and it run just fine.

You can use os.system :

import os
import datetime

path = "/home/xxx/"
current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
command = "mkdir {0}".format(current_time)

os.chdir(path)
os.system(command)

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