Open selfboot opened 7 years ago
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the __name__
set to "__main__
".
__file__
in modelFor the demo.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
print "__file__:", __file__
print "__cwd__:", os.getcwd()
print os.path.dirname(__file__)
print os.path.realpath(__file__)
print "*"*10, "dirname:"
print os.path.dirname(os.path.realpath(__file__))
print os.path.abspath(os.path.dirname(__file__))
Run directly from the script's directory:
$ python demo.py
__file__: demo.py
__cwd__: /Users/f/dropbox
/Users/f/dropbox/demo.py
********** dirname:
/Users/f/dropbox
/Users/f/dropbox
Run from the script's parent directory::
$ python dropbox/demo.py
__file__: dropbox/demo.py
__cwd__: /Users/f
dropbox
/Users/f/dropbox/demo.py
********** dirname:
/Users/f/dropbox
/Users/f/dropbox
From http://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory
Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the
__file__
constant is relative to the current working directory and is not changed by an os.chdir() call.
So, for demo.py as follows:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
print "__file__:", __file__
print "__cwd__:", os.getcwd()
print os.path.dirname(__file__)
print os.path.realpath(__file__)
# change the current working directory.
os.chdir("/home/")
print "__file__:", __file__
print "__cwd__:", os.getcwd()
print os.path.dirname(__file__)
print os.path.realpath(__file__)
Run as:
$ python dropbox/demo.py
__file__: dropbox/demo.py
__cwd__: /Users/feizhao
dropbox
/Users/feizhao/dropbox/demo.py
__file__: dropbox/demo.py
__cwd__: /home
dropbox
/home/dropbox/demo.py
From http://stackoverflow.com/questions/9271464/what-does-the-file-variable-mean-do :
I just want to address some confusion first.
__file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case
__file__
is an attribute of a module (a module object). In Python a .py file is a module. So import a module will have an attribute of__file__
which means different things under difference circumstances.Taken from the docs: