I was trying to write a translate function that could automatically convert some text file in English into Chinese. There is a dictionary saved and the key values are in Chinese characters. However, an error occurred when Python was trying to write to a new text file because it couldn't write in unicode.
Here is my function:
def translateDesc(fileName):
# Opens the file that we're trying to translate
textFile = open(fileName, "r")
print(textFile)
fileLines = textFile.readlines()
textFile.close()
# Creates an output list and translate line by line
outputList = []
for line in fileLines:
outputList.append(translateLines(line)) #outputList now contains some string in Chinese
# Creates an output file and writes in it
outputFile = open("output.txt", "w+")
outputFile.writelines(outputList) # THE ERROR OCCURRED HERE
outputFile.close()
Here is the error message:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-6: character maps to <undefined>
How could I allow Python to write Unicode in a text file?