How to use 'python open utf8' in Python

Every line of 'python open utf8' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
17def open_python_file(filename):
18 """Open a read-only Python file taking proper care of its encoding.
19
20 In Python 3, we would like all files to be opened with utf-8 encoding.
21 However, some author like to specify PEP263 headers in their source files
22 with their own encodings. In that case, we should respect the author's
23 encoding.
24 """
25 import tokenize
26
27 if hasattr(tokenize, "open"): # Added in Python 3.2
28 # Open file respecting PEP263 encoding. If no encoding header is
29 # found, opens as utf-8.
30 return tokenize.open(filename)
31 else:
32 return open(filename, "r")
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

17def open_local(paths, mode='r', encoding='utf8'):
18 path = os.path.join(
19 os.path.abspath(os.path.dirname(__file__)),
20 *paths
21 )
22
23 return codecs.open(path, mode, encoding)

Related snippets