python - Python如何执行没有.py扩展名的文件?

标签 python file-extension

Python 如何执行没有 .py 扩展名的文件?下面的两个文件都有效。 Python 如何知道 hello.txt 是一个 Python 文件?

你好.py:

print "hello world"

你好.txt:

print "hello world"
$ python hello.txt
hello world

$ python hello.py
hello world

最佳答案

Python 知道它是一个 Python 文件,因为你运行了 python <name of file> .文件扩展名实际上对计算机来说并不重要。文件扩展名帮助你,人类,记住什么类型的文件。它们还使计算机更容易自动找出用于特定文件的程序。

但实际上,如果您想忽略文件扩展名,它们根本无关紧要。如果你告诉 Python 打开一个文件,它会尝试打开那个文件。它不关心文件的名称是什么;重要的是文件是否包含有效的 Python 代码。

关于python - Python如何执行没有.py扩展名的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31926207/

相关文章:

python - 导入cv2时出错: 'libSM.so.6: cannot open shared object file: No such file or directory'

java - 使用 CKFinder 上传自定义文件

sqlite - *.sqlite 和 *.db 文件有什么区别?

python - 将列添加到包含先前数据平均值的 Pandas DataFrame 的末尾

python - 将 Keras 集成到 SKLearn 管道?

python - 如果使用 getattr,如何从同一个文件调用函数?

windows - PE/COFF 文件扩展

python - 区分以 .dot 开头的文件扩展名和隐藏文件

javascript - Node js : How to get file signature headers instead of mime-type?

python - 在提示时将密码传递给 Python 脚本