Skip to content

Instantly share code, notes, and snippets.

@spulec
Created March 11, 2013 03:19
Show Gist options
  • Save spulec/5131669 to your computer and use it in GitHub Desktop.
Save spulec/5131669 to your computer and use it in GitHub Desktop.
Read python source file from encoding.
import codecs
import re
opened_file = open(filename, "r")
encoding_line = opened_file.readline()
opened_file.close()
encoding_regex = re.compile('# -\*- coding:(.*) -\*-')
results = re.search(encoding_regex, encoding_line)
if results:
encoding = results.groups()[0]
else:
encoding = 'utf-8'
fp = codecs.open(filename, "r", encoding)
source = fp.readlines()
fp.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment