0

I am trying to save a python-docx document in Ubuntu, but I get this error: 'ascii' codec can't encode character '\xed' in position 65: ordinal not in range(128). I tried to apply this solution, but I get this other error: AttributeError: 'bytes' object has no attribute 'write'.

This is the code that raised the first error:

current_directory = settings.MEDIA_DIR
file_name = "Rooming {} {}-{}.docx".format(hotel, start_date, end_date)
document.save(current_directory + file_name)

This is the code that raised the latest error:

current_directory = settings.MEDIA_DIR
file_name = "Rooming {} {}-{}.docx".format(hotel, start_date, end_date)
document.save((current_directory + file_name).encode('utf-8'))

I know the file name will end having non standard ascii characters, but I would like to be able to save the files using all those characters.

HuLu ViCa
  • 5,077
  • 10
  • 43
  • 93

1 Answers1

0

The problem raised because in Spanish we use some characters modifiers that are not standard (áéíóúüñ), and I was trying to form the name of the file with some data that includes such characters. I guess there must be a way to configure the server so this wouldn't be an issue, but I took the short path and changed the special characters for their standard base character:

current_directory = settings.MEDIA_DIR
file_name = "Rooming {} {}-{}.docx".format(unicodedata.normalize('NFKD', hotel).encode('ascii', 'ignore').decode('ascii'), start_date, end_date)
document.save(current_directory + file_name)

This method replaces characters like this: áéíóúüñÁÉÍÓÚÜÑ -> aeiouunAEIOUUN.

The error desaparead.

HuLu ViCa
  • 5,077
  • 10
  • 43
  • 93