Python文件操作:读写文件路径错误
在Python中,当你尝试读写一个不存在的文件路径时,会抛出FileNotFoundError
异常。
以下是一个示例:
# 错误的路径
wrong_path = '/path/to/a/invalid/file.txt'
try:
# 读取文件
with open(wrong_path, 'r') as file:
print(file.read())
# 写入文件,同样会报错
with open(wrong_path, 'w') as file:
file.write('This is an invalid write.')
except FileNotFoundError as e:
print("Error: ", str(e))
在这个示例中,我们尝试读取和写入一个不存在的文件路径。这会导致FileNotFoundError
异常。
还没有评论,来说两句吧...