Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python execute files without the .py extension?

How is Python able to execute files without the .py extension? Both the files below work. How does Python know that hello.txt is a Python file?

hello.py:

print "hello world"

hello.txt:

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

$ python hello.py
hello world
like image 233
user3270602 Avatar asked Mar 15 '23 03:03

user3270602


1 Answers

Python knows it is a Python file because you ran python <name of file>. File extensions don't actually matter very much to computers. File extensions help you, the human, remember what kind of file something is. They also make it easier for computers to automatically figure out what program to use for a particular file.

But really, file extensions simply don't matter if you want to ignore them. If you tell Python to open a file, it's gonna try to open that file. It doesn't care what the name of the file is; all that matters is if the file contains valid Python code.

like image 90
Hayden Schiff Avatar answered Apr 29 '23 18:04

Hayden Schiff