user1927396
user1927396

Reputation: 459

Creating a folder with timestamp

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()

Upvotes: 17

Views: 49379

Answers (1)

redShadow
redShadow

Reputation: 6777

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

Upvotes: 39

Related Questions