【问题标题】:How may I write Python file at run time?如何在运行时编写 Python 文件?
【发布时间】: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


【解决方案1】:

使用:

fr=open(fp.name,"r")

代替:

fr = open( fp, "r" )

【讨论】:

    【解决方案2】:

    文件名中不能有“:”,使用这个:

    import datetime
    fn = datetime.datetime.now().strftime("%Y-%m-%d %H%M%S") + ".log"
    print fn
    

    给予:

    2016-02-18 174710.log
    

    【讨论】:

      【解决方案3】:

      您的第一个错误可能只是由于拼写错误,您应该通过文件名fn 而不是fp(这是一个文件对象,而不是字符串)打开可读文件。

      第二个错误似乎是由于 Windows 的文件名限制,它不会发生在 Linux 环境中。

      【讨论】:

      • 谢谢。它有效,但我重新发布了这个问题,因为我发布的问题有点错误。
      • 仅供参考,“Thu Feb 18 22:21:35 2016.txt”是一个名为“Thu Feb 18 22”的文件,其流名为“21”,流类型为“35 2016.txt”。后者不是有效的流类型,例如$DATA$INDEX_ALLOCATION。请参阅 File Streams 上的 MSDN。默认类型为$DATA,默认流为匿名,即file.ext等价于file.ext::$DATA。一个目录也可以有$DATA 流,但不能是匿名的;尝试将目录创建或打开为常规文件相当于访问dirname::$DATA,但访问被拒绝。
      猜你喜欢
      • 2022-01-15
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多