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?

  • 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](https://stackoverflow.com/help/how-to-ask). – fpersyn Aug 25 '21 at 08:32
  • The information in the “files” section of this post might be what you are looking for: [https://stackoverflow.com/a/35444608/2550702](https://stackoverflow.com/a/35444608/2550702). – fpersyn Aug 25 '21 at 08:33

1 Answers1

1

Try opening file name with encoding.

file = open(filename, encoding="utf8")
Println
  • 438
  • 1
  • 6
  • 14
  • 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 – user16746929 Aug 25 '21 at 06:28
  • check this link it might help you https://stackoverflow.com/questions/40621799/python-unicodedecodeerror-ascii-codec-cant-decode-byte-0xef-in-position-0/40622844 – Println Aug 25 '21 at 06:45
  • 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. – user16746929 Aug 26 '21 at 04:50