简体   繁体   English

Python - 用循环写入多个文件的函数

[英]Python - function to write multiple files with loop

I'm trying to write a function that would use a loop to write multiple files, but it's not succeeding.我正在尝试编写一个使用循环写入多个文件的函数,但没有成功。 Here are the code, and the result.这是代码和结果。 The directory does exist;该目录确实存在; I was able to write, read, and append single files to it with no problem.我能够毫无问题地写入、读取和附加单个文件。 This was done in the ordinary Python 3.9 interactive command line window on Windows 10.这是在 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'

Unlike "w" or "a" , "r+" requires that the file already exist;不像"w""a""r+"要求文件已经存在; it does not create the file if it does not already exist.如果文件不存在,则不会创建该文件。

You should use a different file mode — such as:您应该使用不同的文件模式——例如:

  • w to open a (possibly new) file, and empty it if it exists. w打开一个(可能是新的)文件,如果存在则清空它。
  • a to open a (possibly new) file, but not empty it. a打开一个(可能是新的)文件,但不清空它。
  • x to open a new file and fail with FileExistsError if it exists . x打开一个新文件,如果存在则失败并显示FileExistsError

As @chepner pointed out, r+ opens an existing file for read and write.正如@chepner指出的那样, r+打开一个现有文件进行读写。

According to this answer you can also use os.mknod("newfile.txt") , but it requires root privilege on macOS.根据此答案,您还可以使用os.mknod("newfile.txt") ,但它需要在 macOS 上具有 root 权限。

It's a bit off-topic, but you might like to know about pathlib , which gives you an OS-agnostic way to handle file paths, and using a context for the file opening, which is safer than open / close .这有点离题,但您可能想了解pathlib ,它为您提供了一种与操作系统无关的方式来处理文件路径,并使用上下文打开文件,这比open / close更安全。 Here's how I'd probably write that function:以下是我可能会编写该函数的方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM