Question

I'm currently looking to create a directory on Linux using Python v2.7 with the directory name as the date and time (ie. 27-10-2011 23:00:01). My code for this is below:-

import time
import os

dirfmt = "/root/%4d-%02d-%02d %02d:%02d:%02d"
dirname = dirfmt % time.localtime()[0:6]
os.mkdir(dirname)

This code works fine and generates the directory as requested. Nonetheless, what I'd also like to then is, within this directory create two csv files and a log file with the same name. Now as the directory name is dynamically generated, I'm unsure as to how to move into this directory to create these files. I'd like the directory together with the three files to all have the same name (csv files will be prefixed with a letter). So for example, given the above, I'd like a directory created called "27-10-2011 23:00:01" and then within this, two csv files called "a27-10-2011 23:00:01.csv" and "b27-10-2011 23:00:01.csv" and a log file called "27-10-2011 23:00:01.log".

My code for the file creations is as below:-

csvafmt = "a%4d-%02d-%02d %02d:%02d:%02d.csv"
csvbfmt = "b%4d-%02d-%02d %02d:%02d:%02d.csv"
logfmt = "%4d-%02d-%02d %02d:%02d:%02d.log"

csvafile = csvafmt % time.localtime()[0:6]
csvbfile = csvbfmt % time.localtime()[0:6]
logfile = logfmt % time.localtime()[0:6]

fcsva = open(csvafile, 'wb')
fcsvb = open(csvbfile, 'wb')
flog = open(logfile, 'wb')

Any suggestions how I can do this so that the second remains the same throughout? I appreciate this code would only take a split second to run but within that time, the second may change. I assume the key to this lies within altering "time.localtime" but I remain unsure.

Thanks

Was it helpful?

Solution

Sure, just save the time in a variable and then use that variable for the substitutions:

now = time.localtime()[0:6]
dirname = dirfmt % now
csvafile = os.path.join(dirname, csvafmt % now)
csvbfile = os.path.join(dirname, csvbfmt % now)
logfile = os.path.join(dirname, logfmt % now)

Edited to include creating the complete path to your csv and log files.

OTHER TIPS

Only call time.localtime once.

current_time = time.localtime()[0:6]

csvafile = csvafmt % current_time 
csvbfile = csvbfmt % current_time 
logfile = logfmt % current_time
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top