From 66c1d4b071b0b6bf7fa51bee84059d042fc96890 Mon Sep 17 00:00:00 2001 From: haosenwang1018 Date: Tue, 24 Feb 2026 18:50:47 +0000 Subject: [PATCH] fix: use context managers and explicit encoding for file operations - read(): Use 'with' statement and utf-8 encoding with error replacement to handle binary files gracefully instead of crashing - edit(): Use 'with' statement and utf-8 encoding to prevent resource leaks on exception paths - grep(): Add utf-8 encoding with error replacement so searching doesn't crash on files with non-UTF-8 content --- nanocode.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/nanocode.py b/nanocode.py index bbe0bf57..047237b6 100755 --- a/nanocode.py +++ b/nanocode.py @@ -22,7 +22,8 @@ def read(args): - lines = open(args["path"]).readlines() + with open(args["path"], encoding="utf-8", errors="replace") as f: + lines = f.readlines() offset = args.get("offset", 0) limit = args.get("limit", len(lines)) selected = lines[offset : offset + limit] @@ -36,7 +37,8 @@ def write(args): def edit(args): - text = open(args["path"]).read() + with open(args["path"], encoding="utf-8") as f: + text = f.read() old, new = args["old"], args["new"] if old not in text: return "error: old_string not found" @@ -67,7 +69,7 @@ def grep(args): hits = [] for filepath in globlib.glob(args.get("path", ".") + "/**", recursive=True): try: - for line_num, line in enumerate(open(filepath), 1): + for line_num, line in enumerate(open(filepath, encoding="utf-8", errors="replace"), 1): if pattern.search(line): hits.append(f"{filepath}:{line_num}:{line.rstrip()}") except Exception: