【问题标题】:Python - function to write multiple files with loopPython - 用循环编写多个文件的函数
【发布时间】:2021-07-23 20:05:36
【问题描述】:

我正在尝试编写一个使用循环来写入多个文件的函数,但它没有成功。这是代码和结果。该目录确实存在;我能够毫无问题地写入、读取和附加单个文件。这是在 Windows 10 上的普通 Python 3.9 交互式命令行窗口中完成的。

def writepages(i):
    for j in range(i):
        name = f"0{j}0page.html"
        file = open(f'C:\\Users\\cumminjm\\Documents\\{name}', 'r+')
        file.close()

>>>
>>> writepages(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in writepages
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\cumminjm\\Documents\\000page.html'

【问题讨论】:

    标签: python


    【解决方案1】:

    不同于"w""a""r+"要求文件已经存在;如果文件尚不存在,则不会创建该文件。

    【讨论】:

      【解决方案2】:

      您应该使用不同的file mode,例如:

      • w 打开一个(可能是新的)文件,如果存在则清空它。
      • a 打开一个(可能是新的)文件,但不要清空它。
      • x 打开一个新文件如果存在FileExistsError 则失败

      正如@chepner 指出的那样,r+ 打开一个现有文件进行读写。

      根据this answer,你也可以使用os.mknod("newfile.txt"),但它需要macOS上的root权限。

      这有点离题,但您可能想了解 pathlib,它为您提供了一种与操作系统无关的方式来处理文件路径,并使用上下文打开文件,这比 open 更安全/close。以下是我可能会如何编写该函数:

      import pathlib
      
      def writepages(i):
          """Write i HTML pages."""
          for j in range(i):
              fname = pathlib.Path.home() / 'Documents' / f'0{j}0page.html'
              with open(fname, 'x') as f:
                  f.write('')
          return
      

      【讨论】:

        猜你喜欢
        • 2014-08-21
        • 1970-01-01
        • 2017-08-28
        • 2022-06-27
        • 1970-01-01
        • 2017-05-27
        • 1970-01-01
        • 2019-05-30
        • 1970-01-01
        相关资源
        最近更新 更多