在Python中生成一个名为当前时间的文本文件
我在Windows8bit-64上使用PythonV2.x 问题是,我未能生成名为real time的txt文件 请查看我现在拥有的代码:在Python中生成一个名为当前时间的文本文件,python,python-2.7,Python,Python 2.7,我在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 =
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=openc:\。。。。但无法创建类似2016-02-16 16:25:02.992000.txt的文本文件
有什么建议吗?在Windows中,:是文件名中的非法字符。您永远无法创建名称类似于16:25:02的文件
此外,您将传递一个元组而不是字符串来打开
试试这个:
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")
可能是文件夹权限问题?您向open函数传递了一个元组,这是不允许的。在python中连接字符串是由string1+string2完成的。修复了我在查看stencil的OP post。Thx Rob,它可以工作!:还有一个问题,我试图替换:to\,但失败了,没有这样的文件或目录。这是否意味着:不能被/?Hi@Amber.G替换。您可以单击Rob回答左侧的复选标记,确认Rob的回答回答了您的问题。@Amber.G\是python中的转义字符,因此您需要使用\\;无论如何,\和/都表示Windows的目录,因此不能用作文件名的一部分。选择其他字符或干脆删除:全部。再见,非常感谢你,罗伯。你的回答被接受了,而且是正确的