您的位置:首页 > 编程语言 > Python开发

os 模块 python file 与文件路径

2014-12-10 19:05 489 查看
eg1:
[root@kooxoo20-180 sersync]# cat test.py
#!/usr/bin/env python
print __file__
[root@kooxoo20-180 sersync]# python test.py
test.py ##me相对路径得到的是相对路径
[root@kooxoo20-180 sersync]# python /home/wuxy/sersync/test.py
/home/wuxy/sersync/test.py ##绝对路径得到的是绝对路径

eg2:
[root@kooxoo20-180 sersync]# cat test.py
#!/usr/bin/env python
import os

a=os.path.realpath(__file__)
print a
[root@kooxoo20-180 sersync]# python test.py
/home/wuxy/sersync/test.py
[root@kooxoo20-180 sersync]# python /home/wuxy/sersync/test.py
/home/wuxy/sersync/test.py ##不管怎么执行,得到的都是绝对路径

eg3:
[root@kooxoo20-180 sersync]# cat test.py
#!/usr/bin/env python
import os

a=os.path.realpath(__file__)
print a
FILE_PATH=os.path.dirname(a)
print FILE_PATH
FILE_PATH=os.path.dirname(os.path.realpath(__file__)) ##建议使用这种方式
print FILE_PATH

[root@kooxoo20-180 sersync]# python test.py
/home/wuxy/sersync/test.py
/home/wuxy/sersync
/home/wuxy/sersync ##调用变量和不使用变量的print值都是一样的

eg4:
[root@kooxoo20-180 sersync]# cat test.py
#!/usr/bin/env python
import os

FILE_PATH=os.path.dirname(os.path.realpath(__file__))
PYCORE_PATH = os.path.realpath(os.path.join(FILE_PATH, '..', 'pycore'))
print PYCORE_PATH
[root@kooxoo20-180 sersync]# pwd
/home/wuxy/sersync
[root@kooxoo20-180 sersync]# python test.py
/home/wuxy/pycore
##me:os.path.join 用 '/' 将各个路径连接起来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  学习 python