iOS Development

ios – Getting Python utilizing os.stroll() to generate a textfile containing the listing construction for a given path

Spread the love

A shot at the hours of darkness with out extra info, however I am guessing that your error appears to be like like this:

Traceback (most up-to-date name final):
  File "", line 16, in <module>
    record_directory_structure("path", "DirectoryStructure.txt")
  File "", line 14, in record_directory_structure
    file.write('{}{}n'.format(subindent, f))
  File "", line 19, in encode
    return codecs.charmap_encode(enter,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec cannot encode characters in place 4-11: character maps to <undefined>

The problem is at this line:

    with open(file_name, "w") as file:

Whenever you open a textual content file, Python must know the encoding for that file. The encoding is a strategy to map logical characters like “letter ‘a’ with acute accent” into precise bytes you could write to a file. Python strings are UTF-8, which is extraordinarily versatile, however has many characters which can be merely untranslatable to different encodings.

The default encoding utilized by open is dependent upon the setting, together with working system, language, and what terminal you are utilizing. You’ll be able to verify what’s your default encoding with this snippet:

import locale
# Prints "cp1252" on my Home windows machine, *not* UTF-8.

So what occurs is that Python noticed a file with Cyrillic/Greek characters, and created strings from it simply high quality (UTF-8). However when writing to the textual content file, the default encoding has no strategy to characterize these characters. Therefore the error.

The answer is to easily specify the file encoding to be UTF-8 too:

def record_directory_structure(directory_path: str, file_name: str):
    #       Add this:         vvvvvvvvvvvvvvvv
    with open(file_name, "w", encoding='utf-8') as file:
        for root, dirs, information in os.stroll(directory_path):
            stage = root.change(directory_path, '').rely(os.sep)
            indent=" " * 4 * (stage)
            file.write('{}{}/n'.format(indent, os.path.basename(root)))
            subindent=" " * 4 * (stage + 1)
            for f in information:
                file.write('{}{}n'.format(subindent, f))

Now you are free to jot down UTF-8 strings to the file, as a result of Python does not must translate the encoding.

One thought on “ios – Getting Python utilizing os.stroll() to generate a textfile containing the listing construction for a given path

  1. Hello Neat post Theres an issue together with your site in internet explorer would check this IE still is the marketplace chief and a large element of other folks will leave out your magnificent writing due to this problem

Leave a Reply

Your email address will not be published. Required fields are marked *