Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建带有时间戳的文件夹_Python - Fatal编程技术网

Python 创建带有时间戳的文件夹

Python 创建带有时间戳的文件夹,python,Python,目前我正在使用下面的代码创建文件,我想根据cwd中该点的时间戳创建一个目录,将目录位置保存到一个变量,然后在新创建的目录中创建文件,有人知道如何做到这一点吗 def filecreation(list, filename): #print "list" with open(filename, 'w') as d: d.writelines(list) def main(): list=['1','2'] filecreation(list,"li

目前我正在使用下面的代码创建文件,我想根据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()

你是说,像这样的

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 ...
完全功能
更新:检查
errno.EEXIST
常量,而不是硬编码错误号

@redShadow谢谢,为什么要检查e.errno=17?17表示什么?编号为17的操作系统错误是“目录存在”,因此,在这种情况下,您可以忽略它(您只需要目录存在),但您不想忽略目录创建失败等情况。感谢RedShadow,谢谢。作为未来任何人的参考,这对我来说都很有效,需要做如下微小的改变:。从日期时间导入日期时间作为dt。作为参考…更多信息,请参考以下注释。{}
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)