Python OS模块重要知识点

Python OS模块重要知识点

这几点很重要,主要是关于文件路径,我之前踩了很多坑,今天总结一下,方便以后能够避免与path相关的各种坑!

1,首先我们想获取某个文件夹下面的所有文件夹以及文件(包括子文件夹里面的文件) 

lists = os.listdir( Path )

2,想获取某个文件夹(Path )下面的所有文件夹以及文件(包括子文件夹里面的文件) 

def listDir( path ):
    for filename in os.listdir(path):
        pathname = os.path.join(path, filename)
        if (os.path.isfile(filename)):
            print pathname
        else:
            listDir(pathname)

3,获取上级目录文件夹:

C:\test\
    getpath.py
    \sub\
         sub_path.py

比如在 sub_path.py 文件里面的这一句代码  os.path.abspath(os.path.dirname(__file__))  可以获取 \sub\ 目录的绝对路径

比如在 sub_path.py 文件里面的这一句代码  os.path.abspath(os.path.dirname(os.path.dirname(__file__)))  可以获取 \test\ 目录的绝对路径

4,获取当前目录及上级目录

└── folder
    ├── data
    │   └── data.txt
    └── test
        └── test.py
print '***获取当前目录***'
print os.getcwd()
print os.path.abspath(os.path.dirname(__file__))

print '***获取上级目录***'
print os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
print os.path.abspath(os.path.dirname(os.getcwd()))
print os.path.abspath(os.path.join(os.getcwd(), ".."))

print '***获取上上级目录***'
print os.path.abspath(os.path.join(os.getcwd(), "../.."))


***获取当前目录***
/workspace/demo/folder/test
/workspace/demo/folder/test

***获取上级目录***
/workspace/demo/folder
/workspace/demo/folder
/workspace/demo/folder

***获取上上级目录***
/workspace/demo

此外:

#curdir  表示当前文件夹
print(os.curdir)

#pardir  表示上一层文件夹
print(os.pardir)

5,调用其他目录的文件时,如何获取被调用文件的路径

C:\test\
    getpath.py
    \sub\
         sub_path.py

比如C:\test目录下还有一个名为sub的目录;C:\test目录下有getpath.py,sub目录下有sub_path.py,getpath.py调用sub_path.py;我们在C:\test下执行getpath.py。

如果我们在sub_path.py里面使用sys.path[0],那么其实得到的是getpath.py所在的目录路径“C:\test”,因为Python虚拟机是从getpath.py开始执行的。

如果想得到sub_path.py的路径,那么得这样:

os.path.split(os.path.realpath(__file__))[0]

其中__file__虽然是所在.py文件的完整路径,但是这个变量有时候返回相对路径,有时候返回绝对路径,因此还要用os.path.realpath()函数来处理一下。

也即在这个例子里,os.path.realpath(__file__)输出是“C:\test\sub\sub_path.py”,而os.path.split(os.path.realpath(__file__))[0]输出才是“C:\test\sub”。

总之,举例来讲,os.getcwd()、sys.path[0] (sys.argv[0])和__file__的区别是这样的:

假设目录结构是:

 C:\test
  |
  [dir] getpath
    |
    [file] path.py
    [dir] sub
      |
      [file] sub_path.py

然后我们在C:\test下面执行python getpath/path.py,这时sub_path.py里面与各种用法对应的值其实是:

os.getcwd() “C:\test”,取的是起始执行目录

sys.path[0]或sys.argv[0] “C:\test\getpath”,取的是被初始执行的脚本的所在目录

os.path.split(os.path.realpath(__file__))[0] “C:\test\getpath\sub”,取的是__file__所在文件sub_path.py的所在目录



猜你喜欢

转载自www.cnblogs.com/111testing/p/9589323.html