Skip to content

Commit 84cdf44

Browse files
committed
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 304: invalid start byte. Fixes #30
1 parent 71bfbf9 commit 84cdf44

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

apps/08_file_searcher/final/program.py

+21-12
Original file line numberDiff line numberDiff line change
@@ -77,18 +77,27 @@ def search_folders(folder, text):
7777

7878

7979
def search_file(filename, search_text):
80-
# matches = []
81-
with open(filename, 'r', encoding='utf-8') as fin:
82-
83-
line_num = 0
84-
for line in fin:
85-
line_num += 1
86-
if line.lower().find(search_text) >= 0:
87-
m = SearchResult(line=line_num, file=filename, text=line)
88-
# matches.append(m)
89-
yield m
90-
91-
# return matches
80+
81+
# NOTE: We haven't discussed error handling yet, but we
82+
# cover it shortly. However, some folks have been running
83+
# into errors where this is passed a binary file and crashes.
84+
# This try/except block catches the error and returns no matches.
85+
try:
86+
87+
# matches = []
88+
with open(filename, 'r', encoding='utf-8') as fin:
89+
90+
line_num = 0
91+
for line in fin:
92+
line_num += 1
93+
if line.lower().find(search_text) >= 0:
94+
m = SearchResult(line=line_num, file=filename, text=line)
95+
# matches.append(m)
96+
yield m
97+
98+
# return matches
99+
except UnicodeDecodeError:
100+
print("NOTICE: Binary file {} skipped.".format(filename))
92101

93102

94103
if __name__ == '__main__':

0 commit comments

Comments
 (0)