Files
Python_CookBook_repo/5.文件与IO/5.对已不存在的文件执行写入操作.py
2025-09-10 16:12:45 +08:00

18 lines
644 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == "__main__":
# 如果想要将数据写入一个已经不在文件系统中的文件可以使用open函数的x模式
try:
path = "5.文件与IO/4.bin_file.bin"
with open(path, 'xt') as f:
f.write("missing file")
# 可以看到,这个写入报了一个文件已存在的错误,如果我们用一个不存在的文件,那就会创建一个新文件成功写入
except FileExistsError:
path = "5.文件与IO/5.missing_file.bin"
with open(path, 'xt') as f:
f.write("missing file")
# 如果需要写入二进制文件同理使用xb就行