Python文件操作:读写与错误处理案例
在Python中,我们可以通过open()
函数进行文件的读写。下面我会提供一些基本的读写案例以及错误处理。
写入文件:
# 创建一个名为'example.txt'的文件
with open('example.txt', 'w') as f:
# 写入内容,这里写入'Hello, World!'
f.write('Hello, World!')
读取文件:
with open('example.txt', 'r') as f:
content = f.read()
print(content) # 输出:Hello, World!
错误处理:
当打开文件或者读写内容时,可能会出现各种错误。比如文件不存在、权限不足等。try:
with open('non_existent_file.txt', 'r') as f:
content = f.read()
print(content) # 这里会抛出FileNotFoundError
except FileNotFoundError:
print("The file does not exist.")
通过以上例子,你可以了解如何在Python中进行文件的读写以及错误处理。
还没有评论,来说两句吧...