0

I am a kind of a newbie in Python. I have multiple configuration files of cisco device in the same path and I want to check whether how many devices were configured Radius IP 10.10.10.4 but when I ran to a file, I found an error as below (problem on some files)

Traceback (most recent call last): File "D:/Test Python/Config file/testoslist.py", line 6, in if '10.10.10.4' in f.read(): File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\encodings\cp874.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 152485: character maps to

import os
import os.path
for fname in os.listdir('.'):
 if os.path.isfile(fname):
    f = open(fname)
    if '10.10.10.4' in f.read():
        print(fname)
       
    f.close()

and If I want to write output to the new file how I can do?

2
  • Welcome to SO! Please make your title relevant to the error you are dealing with, for example "UnicodeDecodeError: 'charmap' codec can't decode byte when reading files in python". This will help others find it easier. For more tips see stackoverflow.com/help/how-to-ask. Commented Aug 25, 2021 at 8:32
  • The information in the “files” section of this post might be what you are looking for: https://stackoverflow.com/a/35444608/2550702. Commented Aug 25, 2021 at 8:33

1 Answer 1

1

Try opening file name with encoding.

file = open(filename, encoding="utf8")
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for helping me. but after added encoding="utf8", I found an error in another file instead, as below (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 357516: invalid continuation byte
check this link it might help you stackoverflow.com/questions/40621799/…
Thank you very much. It's work and I have one more question, If I want to save all output to a new file how do I can. I tried to use with codecs.open("newfile.txt", 'w') as nf: nf.write(fname+ "\n") but it's an overwrite, not continue, the output just has shown last filename.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.