Create dir with datetime name and subfiles within directory (Python)

≡放荡痞女 提交于 2019-12-13 16:03:14

问题


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


回答1:


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.




回答2:


Only call time.localtime once.

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

csvafile = csvafmt % current_time 
csvbfile = csvbfmt % current_time 
logfile = logfmt % current_time


来源:https://stackoverflow.com/questions/7923453/create-dir-with-datetime-name-and-subfiles-within-directory-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!