面试题答案
一键面试在Python中进行文件读取操作时,常见错误有:
- 文件不存在错误(FileNotFoundError):当尝试打开一个不存在的文件时会引发此错误。
try: with open('nonexistent_file.txt', 'r') as file: content = file.read() except FileNotFoundError: print("文件不存在,请检查文件名和路径。")
- 权限错误(PermissionError):当没有足够权限访问文件时会引发此错误。
try: with open('/system/protected_file.txt', 'r') as file: content = file.read() except PermissionError: print("没有权限访问该文件。")
- 编码错误(UnicodeDecodeError):当文件编码与指定编码不匹配时会引发此错误。假设文件实际编码为'gbk',但以'utf - 8'编码读取。
try: with open('file_with_wrong_encoding.txt', 'r', encoding='utf - 8') as file: content = file.read() except UnicodeDecodeError: print("文件编码与指定编码不匹配,请检查编码设置。")