python3获取文件目录和文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import os,sys
if __name__ = = "__main__" :
print ( "__file__ = %s" % __file__)
#获取文件相对路径
print ( "sys.argv[0]) = %s" % sys.argv[ 0 ])
#获取文件的全路径加文件名
print ( "sys.path[0] = %s " % sys.path[ 0 ])
#获取文件的全路径
print ( "os.getcwd() = %s" % os.getcwd())
#获取当前目录路径(和linux的pwd一样)
print ( "os.path.realpath(__file__) = %s " % os.path.realpath(__file__))
#获取文件的全路径加文件名
print ( "os.path.abspath(__file__) = %s " % os.path.abspath(__file__))
#获取文件的绝对路径加文件名
print ( "os.path.dirname(os.path.realpath(__file__)) = %s " % os.path.dirname(os.path.realpath(__file__)))
#获取文件路径
print ( "os.path.basename(os.path.realpath(__file__)) = %s " % os.path.basename(os.path.realpath(__file__)))
#获取文件名
print ( "os.path.split(os.path.realpath(__file__))[0] = %s " % os.path.split(os.path.realpath(__file__))[ 0 ])
#获取文件路径
print ( "os.path.split(os.path.realpath(__file__))[1] = %s " % os.path.split(os.path.realpath(__file__))[ 1 ])
#获取文件名
|
执行结果为:
1
2
3
4
5
6
7
8
9
10
|
C:\Users\Administrator\Desktop>python print.py __file__ = print.py sys.argv[ 0 ]) = print.py
sys.path[ 0 ] = C:\Users\Administrator\Desktop
os.getcwd() = C:\Users\Administrator\Desktop os.path.realpath(__file__) = C:\Users\Administrator\Desktop\print.py os.path.abspath(__file__) = C:\Users\Administrator\Desktop\print.py os.path.dirname(os.path.realpath(__file__)) = C:\Users\Administrator\Desktop os.path.basename(os.path.realpath(__file__)) = print.py os.path.split(os.path.realpath(__file__))[ 0 ] = C:\Users\Administrator\Desktop
|
1
2
3
4
5
6
7
8
9
10
|
D:\>python C:\Users\Administrator\Desktop\print.py __file__ = C:\Users\Administrator\Desktop\print.py sys.argv[ 0 ]) = C:\Users\Administrator\Desktop\print.py sys.path[ 0 ] = C:\Users\Administrator\Desktop os.getcwd() = D:\ os.path.realpath(__file__) = C:\Users\Administrator\Desktop\print.py os.path.abspath(__file__) = C:\Users\Administrator\Desktop\print.py os.path.dirname(os.path.realpath(__file__)) = C:\Users\Administrator\Desktop os.path.basename(os.path.realpath(__file__)) = print.py os.path.split(os.path.realpath(__file__))[ 0 ] = C:\Users\Administrator\Desktop
|