- 論壇徽章:
- 2
|
os模塊
os模塊包裝了不同操作系統(tǒng)的通用接口,使用戶在不同操作系統(tǒng)下,可以使用相同的函數(shù)接口,返回相同結(jié)構(gòu)的結(jié)果。
os.name:返回當(dāng)前操作系統(tǒng)名稱('posix', 'nt', 'os2', 'mac', 'ce' or 'riscos')- In [3]: os.name
- Out[3]: 'posix'
復(fù)制代碼 os中定義了一組文件、路徑在不同操作系統(tǒng)中的表現(xiàn)形式參數(shù)
os.sep(文件夾分隔符,windows中是 \ )
os.extsep(擴(kuò)展名分隔符,windows中是 . )
os.pathsep(目錄分隔符,windows中是 ; )
os.linesep(換行分隔符,windows中是 \r\n )- In [5]: os.sep
- Out[5]: '/'
- In [6]: os.extsep
- Out[6]: '.'
- In [7]: os.pathsep
- Out[7]: ':'
- In [8]: os.linesep
- Out[8]: '\n'
復(fù)制代碼 os中有大量文件、路徑操作的相關(guān)函數(shù)
os.listdir(path):列舉目錄下的所有文件
os.makedirs(path):遞歸式的創(chuàng)建文件夾,注:創(chuàng)建已存在的文件夾將異常
os.remove(filename):刪除一個(gè)文件,刪除目錄會(huì)報(bào)錯(cuò)
os.rmdir(path):刪除一個(gè)文件夾,注:刪除非空的文件夾將異常
os.removedirs(path):遞歸的刪除文件夾,直到有一級(jí)的文件夾非空,注:文件夾路徑不能以'\'結(jié)束,非空目錄會(huì)報(bào)錯(cuò)
os.rename(src,dst):給文件或文件夾改名(可以改路徑,但是不能覆蓋目標(biāo)文件)
os.renames(src,dst):遞歸式的給文件或文件名改名
os.walk(path):列舉path下的所有文件、文件夾- In [10]: os.listdir('/home')
- Out[10]: ['roottest2', 'roottest1', 'nagios', 'test6', 'cacti', 'oracle', 'test7']
- In [12]: os.makedirs('/home/test1223')
- In [13]: os.listdir('/home')
- Out[13]:
- ['test1223',
- 'roottest2',
- 'roottest1',
- ……]
- In [14]: os.remove('/home/test1223')
- ---------------------------------------------------------------------------
- OSError Traceback (most recent call last)
- /root/<ipython console> in <module>()
- OSError: [Errno 21] Is a directory: '/home/test1223'
- In [16]: os.rmdir('/home/test1223')
- In [17]: os.removedirs('/home/a/b/c/')
- ---------------------------------------------------------------------------
- OSError Traceback (most recent call last)
- /root/<ipython console> in <module>()
- /usr/local/lib/python2.7/os.pyc in removedirs(name)
- 168
- 169 ""
復(fù)制代碼 os中與進(jìn)程相關(guān)的操作,如:
os._exit(n):退出程序
os.system('cmd'):運(yùn)行系統(tǒng)命令,會(huì)立即返回,并在cmd執(zhí)行完成后,會(huì)返回cmd退出代碼
os.popen('cmd'):運(yùn)行系統(tǒng)命令,可以把返回值保存到變量
os.path:在不同的操作系統(tǒng)中調(diào)用不同的模塊,可以import
os.getcwd()得到當(dāng)前的工作目錄- In [3]: os.system('ls /home')
- c cacti nagios oracle roottest1 roottest2 test6 test7
- Out[3]: 0
- In [11]: os.getcwd()
- Out[11]: '/root'
復(fù)制代碼 |
|