Home >Backend Development >Python Tutorial >How Can I Replace the Deprecated `execfile()` Function in Python 3?

How Can I Replace the Deprecated `execfile()` Function in Python 3?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 05:26:11324browse

How Can I Replace the Deprecated `execfile()` Function in Python 3?

Alternative to execfile in Python 3

In Python 3, the convenient execfile() function has been deprecated. This has raised concerns among developers who relied on its ability to execute external scripts.

Question:

It seems that Python 3 has eliminated all the easy options for swiftly loading a script, such as execfile(). Am I overlooking a simple solution?

Answer:

Fortunately, there is an alternative method:

To replace:

execfile("./filename")

With:

exec(open("./filename").read())

Further Information:

Refer to the following resources for additional details:

  • [What's New In Python 3.0](https://www.python.org/dev/peps/pep-03104/)
  • [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 How Can I Replace the Deprecated `execfile()` Function in Python 3?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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