[英]Python - function to write multiple files with loop
我正在嘗試編寫一個使用循環寫入多個文件的函數,但沒有成功。 這是代碼和結果。 該目錄確實存在; 我能夠毫無問題地寫入、讀取和附加單個文件。 這是在 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'
不像"w"
或"a"
, "r+"
要求文件已經存在; 如果文件不存在,則不會創建該文件。
您應該使用不同的文件模式——例如:
w
打開一個(可能是新的)文件,如果存在則清空它。a
打開一個(可能是新的)文件,但不清空它。x
打開一個新文件,如果存在則失敗並顯示FileExistsError
。 正如@chepner指出的那樣, r+
打開一個現有文件進行讀寫。
根據此答案,您還可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.