简体   繁体   中英

UTF-8 is not saving txt file correctly - Python

My django application reads a file, and saves some report in other txt file. Everything works fine except my language letters. I mean, encoding="utf-8" can not read some letters. Here are my codes and example of report file:

views.py :

def result(request):
    #region variables
    # Gets the last uploaded document
    last_uploaded = OriginalDocument.objects.latest('id')
    # Opens the las uploaded document
    original = open(str(last_uploaded.document), 'r')
    # Reads the last uploaded document after opening it
    original_words = original.read().lower().split()
    # Shows up number of WORDS in document
    words_count = len(original_words)
    # Opens the original document, reads it, and returns number of characters
    open_original = open(str(last_uploaded.document), "r")
    read_original = open_original.read()
    characters_count = len(read_original)
    # Makes report about result
    report_fives = open("static/report_documents/" + str(last_uploaded.student_name) + 
    "-" + str(last_uploaded.document_title) + "-5.txt", 'w', encoding="utf-8")
    report_twenties = open("static/report_documents/" + str(last_uploaded.student_name) + 
    "-" + str(last_uploaded.document_title) + "-20.txt", 'w', encoding="utf-8")
    # Path to the documents with which original doc is comparing
    path = 'static/other_documents/doc*.txt'
    files = glob.glob(path)
    #endregion

    rows, found_count, fives_count, rounded_percentage_five, percentage_for_chart_five, fives_for_report, founded_docs_for_report = search_by_five(last_uploaded, 5, original_words, report_fives, files)


    context = {
        ...
    }

    return render(request, 'result.html', context)

report file :

['universitetindé™', 'té™hsili', 'alä±ram.', 'mé™n'] was found in static/other_documents\doc1.txt.
...

It's because of Windows OS. Try your application on MacOS it will work without any problem)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM