try: withopen(file_path, mode='w', encoding='utf-8') as f: bytes_written = f.write(file_content) print(f"成功将{bytes_written}字节写入文件:'{file_path}'")
# 逐行读取文件,'r'表示只读 withopen(file_path, mode='r', encoding='utf-8') as f: for line_number, line inenumerate(f, 1): print(f"行{line_number}:{line.strip()}")
except IOError as e: # IOError:文件操作可能出错(如权限不足、磁盘满) print("文件读取(操作)时发生错误")
finally: # finally:无论成功与否,都会执行,用来清理资源(如删文件 if os.path.exists(file_path): os.remove(file_path) print("已删除示例文件")