python操做文件和目錄查看、建立、刪除、複製

python內置了os模塊能夠直接調用操做系統提供的接口函數,os.name查詢的是操做系統,‘nt’表示windows系統python

>>> import os
>>> os.name
'nt'

使用os.environ查看環境變量:windows

>>> os.environ
environ({'ADSK_3DSMAX_X64_2014':AppData\\Roaming', ……})

還能夠得到某個具體的環境變量的值:函數

>>> os.environ.get('path')
'C:\\ProgramData\\Oracle\\Java\\ja……'
>>> os.environ.get('haha','nice') #若是沒有指定的環境變量,則返回指定的值
'nice'

查看當前目錄的絕對路徑:測試

>>> os.path.abspath('.')
'C:\\Users\\WC'

在某個目錄下面建立新目錄,須要兩個步驟:先join(合成路徑),再mkdir()建立spa

>>> os.path.join('E:\Python3.6.3\workspace','測試文件夾')
'E:\\Python3.6.3\\workspace\\測試文件夾'
>>> os.mkdir('E:\\Python3.6.3\\workspace\\測試文件夾')

刪除目錄:操作系統

>>> os.rmdir('E:\\Python3.6.3\\workspace\\測試文件夾')

拆分目錄或者文件的路徑,拆分結果分爲兩部分,後一部分老是最後級別的目錄或者文件名:code

>>> os.path.split('E:\Python3.6.3\workspace\err.py')
('E:\\Python3.6.3\\workspace', 'err.py')
>>> os.path.split('E:\Python3.6.3\workspace')
('E:\\Python3.6.3', 'workspace')

得到文件擴展名,返回的是一個list:對象

>>> os.path.splitext('E:\Python3.6.3\workspace\err.py')
('E:\\Python3.6.3\\workspace\\err', '.py')

重命名:blog

>>> os.rename('E:\\Python3.6.3\\workspace\\err.py','E:\\Python3.6.3\\workspace\\reerr.py')

切換目錄:接口

>>> os.chdir('E:\\Python3.6.3\\workspace\\')
>>> os.path.abspath('.')
'E:\\Python3.6.3\\workspace'

複製文件,須要使用python中高級的文件操做模塊shutil。shutil.copy(s,d)能夠實現文件複製功能,s,d都是字符串格式,s表示源文件,d表示目的文件或者目錄,當d是文件名時,它會被用來當作複製後的文件名稱,效果至關於 複製 +重命名:

>>> import shutil
>>> import os
>>> shutil.copy('first.py','E:\Python3.6.3\workspace\備份')
'E:\\Python3.6.3\\workspace\\備份\\first.py'
>>> shutil.copy('first.py','E:\\Python3.6.3\\workspace\\備份\\first_copy.py')
'E:\\Python3.6.3\\workspace\\備份\\first_copy.py'

(以上注意的是,當重命名一個文件的時候,windows下的目錄路徑要使用\\代替\)

複製文件的內容:

>>> shutil.copyfile('E:\\Python3.6.3\\workspace\\備份\\first.py','E:\\Python3.6.3\\workspace\\備份\\first_copy.py')
'E:\\Python3.6.3\\workspace\\備份\\first_copy.py'

判斷對象是否是目錄\文件:

>>> os.path.isdir('E:\Python3.6.3\workspace\first.py')
False
>>> os.path.isdir('E:\Python3.6.3\workspace')
True
>>> os.path.isfile('E:\Python3.6.3\workspace\hello.py')
True
>>> os.path.isfile('E:\Python3.6.3\workspace')
Fals

練習:列舉指定目錄下包括子目錄中全部的包含指定字符串的文件

>>> import os
>>> def searchStr(d,str):
...     for i in os.listdir(d):
...             sd = os.path.join(os.path.abspath(d),i)
...             if str in i:
...                     print(sd)
...             if os.path.isdir(sd):
...                     searchStr(sd,str)
...
>>> searchStr('E:\Python3.6.3\workspace','f')
E:\Python3.6.3\workspace\err_logginginfo.py
E:\Python3.6.3\workspace\first.py
E:\Python3.6.3\workspace\備份\first.py
E:\Python3.6.3\workspace\備份\first_copy.py
相關文章
相關標籤/搜索