I have some text files with different unknown encoding. Now I have to open a file as binary to detect the encoding first, and open it again with that encoding.
bf = open(f, 'rb')
code = chardet.detect(bf.read())['encoding']
print(f + ' : ' + code)
bf.close()
with open(f, 'r', encoding=code) as source:
texts = extractText(source.readlines())
source.close()
with open(splitext(f)[0] + '_texts.txt', 'w', encoding='utf-8') as dist:
dist.write('\n\n'.join('\n'.join(x) for x in texts))
dist.close()
So is there a better way handle this problem?