目前我正在使用下面的代码创建文件,我想根据cwd中该时间点的时间戳创建一个目录,将目录位置保存到变量然后在新创建的目录中创建文件,是否有人有关于如何做到这一点的想法?
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()
答案 0 :(得分:23)
你的意思是,这样的事情?
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 ...
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)
更新:检查errno.EEXIST
常量,而不是对错误编号进行硬编码