18 lines
644 B
Python
18 lines
644 B
Python
|
|
|||
|
|
|||
|
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就行
|
|||
|
|