Special characters in writing to Python files

2

I'm doing a python script to organize and count words from a text given by a file. I have the problem when printing it to another file.

The code that prints the file is this:

def printToFile(self, fileName):
    file_to_print = open(fileName, 'w')
    file_to_print.write(str(self))
    file_to_print.close()

and here the str of the class called in my other method:

def __str__(self):
    cadena = ""
    for key in self.processedWords:
        cadena += str(key) + ": " + str(self.processedWords[key]) + "\n"
    return cadena.decode('string_escape')

The issue is that if I print it through the console there are no errors, the problem comes when you print it in the file that appear as follows:

This should be the output of the file:

    
asked by Alkesst 03.08.2017 в 22:05
source

1 answer

0

You need to put the headers at the beginning of each file.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

And then you can use the utf-8 encoding in the strings:

def printToFile(self, fileName):
    file_to_print = open(fileName, 'w','utf-8')
    file_to_print.write(str.encode('utf8')(self))
    file_to_print.close()
    
answered by 23.08.2017 / 12:34
source