【发布时间】:2023-03-08 23:55:01
【问题描述】:
我想在 Python 中创建多个文本文件。这些文件将在代码运行时创建。我正在考虑使用
fn = date.today().isoformat() + ".log"
或
>>> from datetime import date
>>> fn=ctime()+".txt"
>>> print fn
Thu Feb 18 22:21:35 2016.txt
这样我就可以始终获得唯一的文件名。但是实验似乎不太顺利,因为我想动态地在其中插入数据,因为它可能来自任何外部来源。发生了一些愚蠢的错误,如下所示,
>>> fn = date.today().isoformat() + ".log"
>>> print fn
2016-02-18.log
>>> quit()
>>> fp = open( fn, "w" )
>>> fp.write( "data" )
>>> fp.close()
>>> fr=open(fp,"r")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
fr=open(fp,"r")
TypeError: coercing to Unicode: need string or buffer, file found
或
>>> fn=ctime()+".txt"
>>> print fn
Thu Feb 18 22:21:35 2016.txt
>>> line1="unanimous resolution to this effect"
>>> fp = open( fn, "w" )
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
fp = open( fn, "w" )
IOError: [Errno 22] invalid mode ('w') or filename: 'Thu Feb 18 22:21:35 2016.txt'
我卡住了。但我的感觉是我可能会犯一些有趣的错误。如果有人可以建议我如何解决问题或解决错误以解决问题。提前致谢。 我在 Windows 10 上使用 Python2.7.11。
【问题讨论】:
-
如果您尝试在文件名中使用冒号,它会做一些奇怪的事情。见Windows Alternate Data Streams
-
Windows 不允许在文件名中使用
:字符。作为替代方案,您还可以使用从调用tempfile.NamedTemporaryFile]()返回的文件对象的.name属性来获得有保证的唯一文件名(尽管它们不会很漂亮)。
标签: python windows python-2.7 python-3.x