2025-09-10:仓库迁移
This commit is contained in:
17
5.文件与IO/5.对已不存在的文件执行写入操作.py
Normal file
17
5.文件与IO/5.对已不存在的文件执行写入操作.py
Normal file
@@ -0,0 +1,17 @@
|
||||
|
||||
|
||||
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就行
|
||||
|
Reference in New Issue
Block a user