Python那点事儿 - OS模块

2020-08-26  本文已影响0人  lupinwu

OS 模块

OS模块是Python内置的模块,通过使用import语句可以直接调用。

import os
In [57]: os.getcwd()
Out[57]: '/Users/lupin/Downloads/test'
In [58]: os.makedirs('d/e/f')

In [59]: ls
a   a1  b   c   d/

In [60]: ls d
e/

In [62]: ls d/e
f/

In [63]: ls d/e/f
In [99]: os.listdir('.')
Out[99]: ['a', 'a1', 'c', 'd', 'b']

os.path 模块

包含了许多与文件名和文件路径相关的有用函数。

In [56]: os.path.join('usr', 'bin', 'spam')
Out[56]: 'usr/bin/spam'
In [64]: os.path.abspath('.')
Out[64]: '/Users/lupin/Downloads/test'

In [68]: os.path.abspath('a')
Out[68]: '/Users/lupin/Downloads/test/a' 
In [69]: os.path.isabs('.')
Out[69]: False

In [71]: os.path.isabs('/Users')
Out[71]: True

In [76]: os.path.isabs(os.path.abspath('.'))
Out[76]: True
In [85]: os.path.relpath('/bin','/')
Out[85]: 'bin'

In [86]: os.path.relpath('/bin')
Out[86]: '../../../../bin'

In [87]: os.getcwd()
Out[87]: '/Users/lupin/Downloads/test'
In [88]: path = '/a/b/c'

In [90]: os.path.dirname(path)
Out[90]: '/a/b'
In [89]: os.path.basename(path)
Out[89]: 'c'
In [91]: os.path.split(path)
Out[91]: ('/a/b', 'c')
In [93]: os.path.sep
Out[93]: '/'

In [94]: path.split(os.path.sep)
Out[94]: ['', 'a', 'b', 'c']
In [97]: os.path.getsize('b')
Out[97]: 13
In [104]: ls -al
total 24
drwxr-xr-x   7 lupin  staff  224 Aug 26 10:18 ./
drwxr-xr-x+ 10 lupin  staff  320 Aug 26 07:44 ../
-rw-r--r--   1 lupin  staff    8 Aug 25 20:27 a
-rw-r--r--   1 lupin  staff    8 Aug 25 20:43 a1
-rw-r--r--   1 lupin  staff   13 Aug 25 20:35 b
-rw-r--r--   1 lupin  staff    0 Aug 25 20:26 c
drwxr-xr-x   3 lupin  staff   96 Aug 26 10:18 d/

In [105]: os.path.exists('a')
Out[105]: True
In [106]: os.path.isfile('a')
Out[106]: True
In [107]: os.path.isdir('a')
Out[107]: False

示例

In [100]: totalsize = 0

In [101]: for filename in os.listdir('.'):
     ...:     totalsize += os.path.getsize(filename)
     ...:

In [102]: totalsize
Out[102]: 125
os.path.exists('d:\\')
上一篇下一篇

猜你喜欢

热点阅读