简体   繁体   中英

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.

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; 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.
  • a to open a (possibly new) file, but not empty it.
  • x to open a new file and fail with FileExistsError if it exists .

As @chepner pointed out, r+ opens an existing file for read and write.

According to this answer you can also use os.mknod("newfile.txt") , but it requires root privilege on macOS.

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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