在Python中生成一个文本文件,文件名为当前时间

2024-09-30 12:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows8bit-64上使用pythonv2.x。在

问题是,我未能生成名为real-time的txt文件。在

请看我现在的代码:

import sys
import datetime

def write():

    # try:
        currentTime = str(datetime.datetime.now())
        print currentTime #output: 2016-02-16 16:25:02.992000
        file = open(("c:\\", currentTime, ".txt"),'a')   # Problem happens here
        print >>file, "test"
        file.close()

我尝试了不同的方法来修改file=open((“c:\…..)”行,但未能创建像2016-02-16 16:25:02.992000.txt这样的文本文件

有什么建议吗?在


Tags: 文件代码importtxtdatetimetimedefsys
2条回答

在Windows中,:是文件名中的非法字符。您永远不能创建一个名为16:25:02的文件。在

另外,您正在将元组而不是字符串传递给open。在

试试这个:

    currentTime = currentTime.replace(':', '_')
    file = open("c:\\" + currentTime + ".txt",'a')

这里有一种更有效的方法来编写代码。在

import sys
import datetime

def write():
        currentTime = str(datetime.datetime.now())
        currentTime = currentTime.replace(':', '_')
        with open("c:\\{0}.txt".format(currentTime), 'a') as f:
             f.write("test")

相关问题 更多 >

    热门问题