您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python中文件操作与异常的处理是怎样的
## 1. 文件操作基础
### 1.1 打开文件
在Python中,使用`open()`函数来打开文件,基本语法如下:
```python
file = open(filename, mode)
常用模式:
- 'r'
:只读(默认)
- 'w'
:写入(会覆盖原有内容)
- 'a'
:追加
- 'b'
:二进制模式
- '+'
:读写模式
# 读取整个文件
content = file.read()
# 逐行读取
for line in file:
print(line)
# 读取单行
line = file.readline()
file.write("Hello, Python!\n")
file.writelines(["line1\n", "line2\n"])
file.close()
推荐使用with
语句自动管理文件资源:
with open('example.txt', 'r') as file:
content = file.read()
# 文件会自动关闭
try:
# 可能出错的代码
file = open('nonexistent.txt', 'r')
except FileNotFoundError:
# 处理特定异常
print("文件不存在!")
except Exception as e:
# 处理其他异常
print(f"发生错误:{e}")
try:
# 尝试执行的代码
pass
except SpecificError:
# 处理特定异常
pass
except (ErrorType1, ErrorType2):
# 处理多个异常
pass
except Exception as e:
# 处理未预料到的异常
print(f"未知错误:{e}")
else:
# 没有异常时执行
pass
finally:
# 无论是否发生异常都会执行
pass
try:
with open('missing.txt') as f:
pass
except FileNotFoundError:
print("文件未找到,请检查路径")
try:
with open('/root/file.txt', 'w') as f:
pass
except PermissionError:
print("没有写入权限")
try:
with open('/etc', 'r') as f:
pass
except IsADirectoryError:
print("这是一个目录,不是文件")
def safe_copy(src, dst):
try:
with open(src, 'rb') as src_file:
with open(dst, 'wb') as dst_file:
dst_file.write(src_file.read())
print("文件复制成功")
except FileNotFoundError:
print("源文件不存在")
except PermissionError:
print("没有操作权限")
except Exception as e:
print(f"复制失败:{e}")
safe_copy('source.txt', 'destination.txt')
def log_message(message):
try:
with open('app.log', 'a') as log_file:
log_file.write(f"{datetime.now()}: {message}\n")
except IOError as e:
print(f"无法写入日志:{e}")
log_message("系统启动")
with open('file.txt', 'r', encoding='utf-8') as f:
pass
Python的文件操作和异常处理机制提供了强大而灵活的工具: - 文件操作API简单直观 - 异常处理能有效预防和解决问题 - 上下文管理器简化了资源管理 - 合理的错误处理能提升程序健壮性
通过结合文件操作和异常处理,可以编写出既强大又可靠的Python程序。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。