Home > Backend Development > Python Tutorial > What's the Python 3 Equivalent of `execfile()`?

What's the Python 3 Equivalent of `execfile()`?

Patricia Arquette
Release: 2024-12-06 22:43:13
Original
844 people have browsed it

What's the Python 3 Equivalent of `execfile()`?

Alternative to execfile in Python 3

In previous versions of Python, execfile() provided a convenient way to load and execute external scripts. However, Python 3 discontinued this function, leaving many users wondering for an alternative solution.

Easy Script Loading in Python 3

To overcome the absence of execfile(), Python 3 offers a straightforward alternative: exec(open(file_name).read()). This syntax effectively reads the contents of the external script into a string, then executes it using the exec() function.

For example:

exec(open("./filename").read())
Copy after login

Documentation References

  • [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html#whatsnew-3.0)
  • [execfile](https://docs.python.org/2/library/functions.html#execfile)
  • [exec](https://docs.python.org/3/library/functions.html#exec)

The above is the detailed content of What's the Python 3 Equivalent of `execfile()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template