Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a folder with timestamp

Tags:

python

Currently am creating files using the below code,I want to create a directory based on the timestamp at that point in the cwd,save the directory location to a variable and then create the file in the newly created directory,does anyone have ideas on how can this be done?

def filecreation(list, filename):
    #print "list"
    with open(filename, 'w') as d:
        d.writelines(list)

def main():
    list=['1','2']
    filecreation(list,"list.txt")

if __name__ == '__main__':
    main()
like image 365
user1927396 Avatar asked Jan 01 '13 23:01

user1927396


People also ask

How do I create a time stamp folder?

Step 1: Firstly, navigate to the parent folder where you want to create the folder and name it based on the system's current timestamp. As next, right click on an empty space, click on New and then click on the Text Document option. Step 2: Now double click on the newly created text document to edit it.

How do I put the current date and time in a folder?

For a Windows batch-file, you'd just use mkdir "%DATE%" or mkdir "%datestamp%" -- whichever variable you want to use.

What is a time stamped directory?

These allow you to determine when a file or folder was created, when it was last updated and the time that it was most recently accessed.


1 Answers

You mean, something like this?

import os, datetime
mydir = os.path.join(os.getcwd(), datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
os.makedirs(mydir)
with open(os.path.join(mydir, 'filename.txt'), 'w') as d:
    pass # ... etc ...

Complete function

import errno
import os
from datetime import datetime

def filecreation(list, filename):
    mydir = os.path.join(
        os.getcwd(), 
        datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
    try:
        os.makedirs(mydir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise  # This was not a "directory exist" error..
    with open(os.path.join(mydir, filename), 'w') as d:
        d.writelines(list)

Update: check errno.EEXIST constant instead of hard-coding the error number

like image 140
redShadow Avatar answered Oct 29 '22 09:10

redShadow