0

I'm doing a course of python on py4e, almost done, but chapter 11 seems like impossible because it gives me error every time.

Error:

line 4, in <module>
    lines = ffail.read()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 8: invalid continuation byte

Code:

import re

ffail = open('regex_sum_340933.txt')
lines = ffail.read()
count = 0

match = re.findall('[0-9]+', lines)

for II in match:
    number = int(II)
    count = count + number
print(count)
deadshot
  • 8,881
  • 4
  • 20
  • 39

3 Answers3

0

You are not doing it right. first of all you need to close the file I would suggest

to just use with so you won't need to worry about closing the file.

replace how you read the file with this

ffail = ""
with open("regex_sum_340933.txt", mode = "r" ,encoding='UTF-8', errors='ignore',  buffering=-1) as some_file:
    ffail = some_file.read()

make sure that regex_sum_340933.txt is in the same directory as the file of the code.

if you are still having difficulties you could visit this question

Patch
  • 694
  • 1
  • 10
  • 29
  • Could you please accept the question/explain why it doesn't work and where is the problem? – Patch May 13 '20 at 10:48
  • Is the code supposed to look like this? import re ffail = "" with open("regex_sum_340933.txt", "r" , "UTF-8") as some_file: ffail = some_file.read() count = 0 match = re.findall('[0-9]+', ffail) for II in match: number = int(II) count = count + number print(count) Gives this ERROR: line 4, in with open("regex_sum_340933.txt", "r" , "UTF-8") as some_file: TypeError: an integer is required (got type str). I don't understand what I need to do. – Rome Esna May 14 '20 at 11:27
  • @RomeEsna Try and update your code with the err I can't understand – Patch May 14 '20 at 12:58
  • with open("regex_sum_340933.txt", "r" , "UTF-8") as some_file: TypeError: an integer is required (got type str) It gives me this error, any suggestions? – Rome Esna May 15 '20 at 09:57
  • @RomeEsna See updated answer try with and without the `buffering` and show me the error if there is one – Patch May 15 '20 at 13:07
0

Try this:

import re

lines = open('regex_sum_340933.txt', encoding='utf-8', errors='ignore').read()
count = sum(map(int, re.findall('[0-9]+', lines)))
deadshot
  • 8,881
  • 4
  • 20
  • 39
0

thanks for helping, the code wasn't wrong, just my Mac didn't want to make it work. Tried with windows and the answer came immediately.