use*_*602 6 python file-extension
Python 如何执行没有 .py 扩展名的文件?下面的两个文件都有效。Python 如何知道这hello.txt是一个 Python 文件?
hello.py:
print "hello world"
Run Code Online (Sandbox Code Playgroud)
hello.txt:
print "hello world"
Run Code Online (Sandbox Code Playgroud)
$ python hello.txt
hello world
$ python hello.py
hello world
Run Code Online (Sandbox Code Playgroud)
Python 知道它是一个 Python 文件,因为你运行了python <name of file>. 文件扩展名实际上对计算机来说并不重要。文件扩展名可以帮助您(人类)记住某文件是什么类型。它们还使计算机更容易自动找出对特定文件使用什么程序。
但实际上,如果您想忽略文件扩展名,它们根本就不重要。如果你告诉 Python 打开一个文件,它会尝试打开该文件。它不关心文件的名称是什么;重要的是该文件是否包含有效的 Python 代码。