0

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'
Matt Hall
  • 7,614
  • 1
  • 23
  • 36
ekwas
  • 19
  • 2

2 Answers2

0

Unlike "w" or "a", "r+" requires that the file already exist; it does not create the file if it does not already exist.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

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
Matt Hall
  • 7,614
  • 1
  • 23
  • 36