Alternatives to execfile in Python 3
Python 3's removal of execfile() has left many wondering how to swiftly load scripts. While execfile() may be gone, alternative options exist.
Solution:
The documentation recommends using the exec() function with the contents of the file passed as an argument:
exec(open("filename").read()) # Replaces execfile("filename")
Explanation:
execfile() parsed and executed a file, while exec() executes a string. By reading the file contents into a string and passing them to exec(), we achieve the same effect as execfile().
Additional Considerations:
Further Reading:
The above is the detailed content of How Can I Replace Python 2's `execfile()` in Python 3?. For more information, please follow other related articles on the PHP Chinese website!