0

I have script that could be run on PC with English or Russian locale. The script writes some data to csv file:

with open(FILE_NAME, 'w', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=CSV_DELIMITER)
    writer.writeheader()

The problem is that delimiter in English locale is comma (,) and in Russian locale, it is semicolon (;). For now I' ve solved it by analyzing locale ('en' or 'ru') and sending delimiter specific for current locale to code that writes data to csv file:

def get_csv_delimiter():
    default_locale = locale.getdefaultlocale()
    language_code = default_locale[0][0:2]
    if language_code in ['en']:
        delimiter = ','
    elif language_code in ['ru']:
        delimiter = ';'
    return delimiter

But if I need to add other locales I add new if's or dictionary kind of {locale: locale_delimeter} to get_csv_delimiter function. Is there any simplier way to get delimiter for current locale?

Onur A.
  • 3,007
  • 3
  • 22
  • 37
Aleks Lee
  • 136
  • 1
  • 1
  • 10
  • 1
    note: `if language_code in ['en']` => `if language_code == 'en'` – Jean-François Fabre Sep 25 '17 at 19:53
  • For your use-case, using a dictionary would be appropriate. Have you tried and facing any difficulty? – balki Sep 25 '17 at 20:11
  • I think you are talking different worlds for locale and csv dialect. Determining a locale does not guarantee a delimiter for you in any way. The program or the user who produced a CSV could have used any delimiter on any locale. – Evgeny Sep 25 '17 at 20:19

0 Answers0