Python 學習筆記 (7)—— OS模塊

os 模塊,正如其名,主要與操做系統打交道的,下面介紹下一些常見的功能
1、文件與目錄操做
node

一、os.getcwd()    獲取當前路徑
>>> import os
>>> os.getcwd()
'/tmp/python'
python

 

二、os.listdir()    列出目錄中的內容
>>> import os
>>> os.listdir(os.getcwd())
['esc.py', '7.py', 'cat1.py', 'say.pyc', '2.py', 'backup_ver1.py', '5.py', '8.py', 'count.py', '3.py', 'replace.py', 'p_w_picpath']
web

注意,經過這個方法只能以列表的形式列出全部文件,但不能遍歷該目錄下的子目錄shell

 

三、os.mkdir()    建立目錄
>>> import os
>>> os.mkdir('/tmp/testdir')

[root@node1 python]# ls /tmp/testdir/ -d
/tmp/testdir/
vim

 

經過os.mkdir 只能建立一級目錄,若是父目錄不存在,則會報錯:windows

>>> import os
>>> os.mkdir('/testdir/dirs')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '/testdir/dirs'
bash

 

一次性建立嵌套目錄可以使用os.makedirs,makedirs能夠生成多層遞歸目錄,removedirs能夠刪除多層遞歸的空目錄,若目錄中有文件則沒法刪除less

 

>>> import os
>>> os.makedirs('/testdir/dirs')
>>> os.system('ls -ld /testdir/dirs')
drwxr-xr-x. 2 root root 4096 Dec  3 20:52 /testdir/dirs
0
ssh

 

四、os.rmdir()    刪除目
>>> import os
>>> os.rmdir('/testdir/dirs')

>>> os.system('ls -l /testdir/dirs')
ls: cannot access /testdir/dirs: No such file or directory
512
ide

目錄必須爲空,不然會報錯

[root@node1 tmp]# mkdir testdir
[root@node1 tmp]# touch testdir/a

>>> import os
>>> os.rmdir('/tmp/testdir')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 39] Directory not empty: '/tmp/testdir'

若是要刪除能夠藉助os.system() 執行shell命令強行刪除


>>> import os
>>> os.system('rm -rf /tmp/testdir')
0
>>> os.system('ls -l /tmp/testdir')
ls: cannot access /tmp/testdir: No such file or directory
512

 

五、os.chdir()    改變目錄
>>> import os
>>> os.getcwd()
'/tmp/python'
>>> os.chdir('/etc')
>>> os.getcwd()
'/etc'

 

六、os.remove()    刪除文件
>>> import os
>>> os.remove('/tmp/python/1.py')

 

七、os.rename(原文件名,改變文件名)    重命名文件或目錄
>>> import os
>>> os.rename('/tmp/test.txt','/tmp/python.txt')

>>> os.system('ls -l /tmp/*.txt')
-rw-r--r--. 1 root root 47 Dec  2 06:16 /tmp/myhello.txt
-rw-r--r--. 1 root root 82 Dec  2 06:18 /tmp/python.txt
0


os.renames()    遞歸的給目錄重命名

>>> import os
>>> os.rename('/tmp/test/subdir','/tmp/test1/subdir1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory

>>> os.renames('/tmp/test/subdir','/tmp/test1/subdir1')
>>> os.system('ls -ld /tmp/test1/subdir1')
drwxr-xr-x. 2 root root 4096 Dec  4 20:06 /tmp/test1/subdir1
0

 

八、os.system()    執行shell 命令
>>> import os
>>> os.system('ls /tmp')
backup  myhello.txt  python  python.txt  test  yum.log
0

 

九、os 模塊屬性
>>> os.curdir    #當前工做目錄的字符串名稱
'.'
>>> os.pardir    #(當前工做目錄的)父目錄字符串名稱
'..'
>>> os.linesep    #用於在文件中分隔行的字符串
'\n'
>>> os.sep    #用來分隔文件路徑名的字符串
'/'
>>> os.pathsep    #用於分隔文件路徑的字符串
':'

 

這個屬性在寫腳本的時候比較有用,好比在寫備份腳本的時候,指定存放備份的路徑能夠這樣:
>>> import time
>>> filename = time.strftime('%H%M%S')
>>> target_dir = '/tmp/backup'
>>> dirname = target_dir + time.strftime('%Y%m%d')
>>> target = dirname + os.sep + filename + '.tar.gz'

 

十、os.stat()    返回文件的屬性
>>> import os
>>> os.stat('/tmp/python.txt')
posix.stat_result(st_mode=33188, st_ino=924858, st_dev=64768L, st_nlink=1, st_uid=0, st_gid=0, 
st_size=82, st_atime=1385936299, st_mtime=1385936293, st_ctime=1386076480)

 

能夠經過字典遍歷


#!/usr/bin/python
import os
import stat
import time
fileStats = os.stat('/tmp/python.txt')
fileInfo = {
        'Size':fileStats[stat.ST_SIZE],
        'LastModified':time.ctime(fileStats[stat.ST_MTIME]),
        'LastAccessed':time.ctime(fileStats[stat.ST_ATIME]),
        'CreationTime':time.ctime(fileStats[stat.ST_CTIME]),
        'Mode':fileStats[stat.ST_MODE]
}

for infoField,infoValue in fileInfo.iteritems():
        print infoField, ':' ,infoValue

[root@node1 python]# python stat.py
LastModified : Mon Dec  2 06:18:13 2013
Mode : 33188
CreationTime : Tue Dec  3 21:14:40 2013
LastAccessed : Mon Dec  2 06:18:19 2013
Size : 82

 

十一、os.walk()   遍歷目錄
函數聲明:walk(top,topdown=True,onerror=None)

1>參數top表示須要遍歷的目錄樹的路徑

 

2>參數topdown的默認值是"True",表示首先返回目錄樹下的文件,而後在遍歷目錄樹的子目錄.Topdown的值爲"False"時,則表示先遍歷目錄樹的子目錄,返回子目錄下的文件,最後返回根目錄下的文件

 

3>參數onerror的默認值是"None",表示忽略文件遍歷時產生的錯誤.若是不爲空,則提供一個自定義函數提示錯誤信息後繼續遍歷或拋出異常停止遍歷

 

4>該函數返回一個元組,該元組有3個元素,這3個元素分別表示每次遍歷的路徑名,目錄列表和文件列表

 

#!/usr/bin/python
import os
def visitDir(path):
        for root,dirs,files in os.walk(path):
                for filespath in files:
                        print os.path.join(root,filespath)
if __name__ == "__main__":
        path = "/root"
        visitDir(path)

[root@node1 python]# python walk.py 
/root/.bash_history
/root/install.log.syslog
/root/.bash_profile
/root/.viminfo
/root/anaconda-ks.cfg
/root/.bash_logout
/root/init.sh
/root/.cshrc
/root/.bashrc
/root/.tcshrc
/root/.lesshst
/root/install.log
/root/webproject/manage.py
/root/webproject/webproject/wsgi.pyc
/root/webproject/webproject/wsgi.py
/root/webproject/webproject/settings.pyc
/root/webproject/webproject/settings.py

 

十二、獲取系統信息
>>> import os
>>> os.uname()    #獲取當前系統信息
('Linux', 'node1', '2.6.32-279.el6.x86_64', '#1 SMP Wed Jun 13 18:24:36 EDT 2012', 'x86_64')
>>> os.getuid()   #獲取當前用戶ID
0
>>> os.getgid()   #獲取當前組ID
0
>>> os.getpid()   #獲取當前進程ID
1239
>>> os.getpgrp()   #獲取當前進程組ID
1239
>>> os.ctermid()   #獲取當前使用終端
'/dev/tty'
>>> os.getlogin()   #獲取當前登陸的用戶名
'root'

 

2、權限
1三、os.access(路徑,uid/gid)  
  測試指定uid/gid 對指定目錄有沒有權限,有權限返回True,無權限返回False
>>> import os
>>> os.access('/tmp/test')

>>> os.access('/tmp/test',0)
True
>>> os.access('/tmp/test',33)
False

 

1四、os.chmod(路徑,權限)    修改文件/目錄 權限
>>> import os
>>> os.chmod ('/tmp/python.txt',0775)
>>> os.system('ls -l /tmp/python.txt')
-rwxrwxr-x. 1 root root 82 Dec  2 06:18 /tmp/python.txt
0

 

1五、os.chown(路徑,UID,GID)    修改擁有者,屬組
>>> import os
>>> os.chown('/tmp/python.txt',500,500)
>>> os.system('ls -l /tmp/python.txt')
-rwxrwxr-x. 1 python python 82 Dec  2 06:18 /tmp/python.txt
0

 

3、os.path 模塊
1六、os.path.basename()    去掉目錄路徑, 返回文件名
>>> import os.path
>>> os.path.basename('/tmp/python.txt')
'python.txt'

 

1七、os.path.dirname()    去掉文件名, 返回目錄路徑
>>> import os.path
>>> os.path.dirname('/tmp/python.txt')
'/tmp'

 

1八、os.path.join()   將分離的各部分組合成一個路徑名
>>> import os.path
>>> dir = '/tmp'
>>> file = 'python.txt'
>>> os.path.join(dir,file)
'/tmp/python.txt'

 

1九、
os.path.getatime()     返回最近訪問時間
os.path.getctime()     返回文件建立時間
os.path.getmtime()    返回最近文件修改時間

>>> import os.path
>>> os.path.getatime('/tmp/python.txt')
1385936299.3662264
>>> os.path.getctime('/tmp/python.txt')
1386107618.3203411
>>> os.path.getmtime('/tmp/python.txt')
1385936293.4863505

 

但這樣看到的時間,是計算當前時間距離1970年1月1日的秒數的,不人性化,能夠這樣顯示
>>> import os.path
>>> import time

>>> time.ctime(os.path.getatime('/tmp/python.txt'))
'Mon Dec  2 06:18:19 2013'
>>> time.ctime(os.path.getctime('/tmp/python.txt'))
'Wed Dec  4 05:53:38 2013'
>>> time.ctime(os.path.getmtime('/tmp/python.txt'))
'Mon Dec  2 06:18:13 2013'

 

20、os.path.getsize()   返回文件大小(以字節爲單位)
>>> import os.path
>>> os.path.getsize('/tmp/python.txt')
82

 

2一、os.path.exists()    指定路徑(文件或目錄)是否存在 
>>> import os.path
>>> os.path.exists('/tmp/python.txt')
True
>>> os.path.exists('/tmp/python')
False

 

2二、
os.path.isdir()     指定路徑是否存在且爲一個目錄
os.path.isfile()    指定路徑是否存在且爲一個文件

>>> import os.path
>>> os.path.isdir('/tmp/python.txt')
False
>>> os.path.isdir('/tmp/')
True
>>> os.path.isfile('/tmp')
False
>>> os.path.isfile('/tmp/python.txt')
True

 

os.path.exists()    判斷指定路徑是否存在

>>> import os.path
>>> os.path.exists('/tmp/')
True
>>> os.path.exists('/tmpp/')
False

 

2三、os.path.splitext()   分隔文件名和後綴名
>>> import os.path
>>> os.path.splitext('python.txt')
('python', '.txt')

========================
其餘 os 模塊函數
文件處理
mkfifo()/mknod()    建立命名管道/建立文件系統節點
remove()/unlink()    刪除文件 os.remove()函數用來刪除一個文件。
symlink()                  建立符號連接
utime()                     更新時間戳
tmpfile()                   建立並打開('w+b')一個新的臨時文件

 

目錄/文件夾
chroot()                     改變當前進程的根目錄
getcwdu()                 返回當前工做目錄並返回一個 Unicode 對象 os.getcwd()函數獲得當前工做目錄,即當前Python腳本工做的目錄路徑。
makedirs()                 建立目錄/建立多層目錄
removedirs()             刪除多層目錄

 

文件描述符操做
open()                      底層的操做系統 open (對於文件, 使用標準的內建 open() 函數)
read()/write()           根據文件描述符讀取/寫入數據
dup()/dup2()           複製文件描述符號/功能相同, 可是是複製到另外一個文件描述符

 

設備號
makedev()               從 major 和 minor 設備號建立一個原始設備號
major()/minor()      從原始設備號得到 major/minor 設備號

 

系統操做
os.name                        字符串指示你正在使用的平臺。好比對於Windows,它是'nt',而對於Linux/Unix用戶,它是'posix'。
os.getenv()                    獲取一個環境變量,若是沒有返回none
os.putenv(key, value)   設置一個環境變量值

 

分隔符
os.sep()                        文件夾分隔符,windows中是 / os.extsep()                  擴展名分隔符,windows中是 . os.pathsep()               目錄分隔符,windows中是 ; os.linesep()                 換行分隔符,windows中是 /r/n 

相關文章
相關標籤/搜索