How to use 'python open' in Python

Every line of 'python open' 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
17def open_python_file(filename):
18 """Open a read-only Python file taking proper care of its encoding.
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
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
31 else:
32 return open(filename, "r")

Related snippets