nidhaloff / deep-translator

A flexible free and unlimited python tool to translate between different languages in a simple way using multiple translators.
https://deep-translator.readthedocs.io/en/latest/?badge=latest
Apache License 2.0
1.61k stars 185 forks source link

How to save translated text to a file? #232

Closed SoftologyPro closed 1 year ago

SoftologyPro commented 1 year ago

None of the examples show how to save the translated txt to a file.

For example, how can I save the txt to a new file in this code? translated.save does not work.

from deep_translator import GoogleTranslator
translated = GoogleTranslator(source='auto', target='en').translate_file('german.txt')
translated.save('translated.txt') 
print(f"{translated}")

Then I can loop through multiple files hands free and have the output translations saved to txt files.

PrashantDixit0 commented 1 year ago

You can use following code snippet for saving translated text into text file

text_file = open("translated.txt) 
text_file.write(translated)
text_file.close()
SoftologyPro commented 1 year ago

Thanks, using this code

from deep_translator import GoogleTranslator
translated = GoogleTranslator(source='auto', target='en').translate_file('german.txt')
text_file = open("english.txt")
text_file.write(translated)
text_file.close()
print(f"{translated}")

gives this error now

Traceback (most recent call last):
  File "C:\DeepTranslator\test2.py", line 3, in <module>
    text_file = open("english.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'english.txt'
nidhaloff commented 1 year ago

You can simply open a file and write to it using plain python. Here is an example:

# Writing to file
with open("myfile.txt", "w") as f:
    # Writing data to a file
    f.write(translated)