Python开发中的常见文件操作错误处理实例
在Python的文件操作中,常见的错误包括但不限于文件不存在、权限不足、读写错误等。以下是一些错误处理的例子:
- 文件不存在:
```python
filename = “non_existent_file.txt”
try:
with open(filename, ‘r’) as f:
print(f.read())
except FileNotFoundError:
print(“File not found: “, filename)
2. 权限不足:
```python
def write_to_system_file(filename, content):
try:
with open(filename, 'w') as file:
file.write(content)
return True
except PermissionError:
print("Permission error occurred while writing to system file.")
return False
filename = "/etc/passwd"
content = "test_user:12345:$6$PcYjR3B0tO19bVJqZQ=="
if write_to_system_file(filename, content):
print("Successfully wrote to system file.")
else:
print("Failed to write to system file.")
以上例子中,我们使用了try/except来捕获可能出现的错误,并进行适当的处理。
还没有评论,来说两句吧...