用Python目錄創(chuàng)建及應(yīng)用
Python目錄是計算機(jī)語言常用的語言,可是很多人還是對其不太了解,覺得它的實際應(yīng)用語言操作太難,其實如果你了解了Python目錄的操作技能,你對其就有個更深的了解。你如果感興趣的話,就看看下面的文章吧!
和普通文件一樣,關(guān)于Python目錄的操作也很容易掌握。首先,列出一個目錄的內(nèi)容:
- view plaincopy to clipboardprint?
- import os
- for fileName in os.listdir ( '/' ):
- print fileName
- import os
- for fileName in os.listdir ( '/' ):
print fileName正如你所見,這很簡單,用三行代碼就可以完成。
創(chuàng)建目錄也很簡單:
- view plaincopy to clipboardprint?
- import os
- for fileName in os.listdir ( '/' ):
- print fileName
- import os
- for fileName in os.listdir ( '/' ):
刪除剛才創(chuàng)建的Python目錄:也可以創(chuàng)建多級目錄:
- view plaincopy to clipboardprint?
- import os
- os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
- import os
- os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
如果沒有在創(chuàng)建的文件夾中添加任何東西,就可以一次性將它們?nèi)縿h除(即,刪除所列的所有空文件夾):
- view plaincopy to clipboardprint?
- import os
- os.removedirs( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
- import os
- os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
當(dāng)需要對一個特定的文件類型進(jìn)行操作時,我們可以選擇“fnmatch”模塊。以下是顯示“.txt”文件的內(nèi)容和“.exe”文件的文件名:
- view plaincopy to clipboardprint?
- import fnmatch
- import os
- for fileName in os.listdir ( '/' ):
- if fnmatch.fnmath ( fileName, '*.txt' ):
- print open ( fileName ).read()
- elif fnmatch.fnmatch ( fileName, '*.exe' ):
- print fileName
- import fnmatch
- import os
- for fileName in os.listdir ( '/' ):
- if fnmatch.fnmath ( fileName, '*.txt' ):
- print open ( fileName ).read()
- elif fnmatch.fnmatch ( fileName, '*.exe' ):
- print fileName“*”
字符可以表示任意長度的字符。如果要匹配一個字符,則使用“?”符號:
- view plaincopy to clipboardprint?
- import fnmatch
- import os
- for fileName in os.listdir ( '/' ):
- if fnmatch.fnmatch ( fileName, '?.txt' ):
- print 'Text file.'
- import fnmatch
- import os
- for fileName in os.listdir ( '/' ):
- if fnmatch.fnmatch ( fileName, '?.txt' ):
- print 'Text file.'“fnmatch”
以上就是對關(guān)于Python目錄具體操作內(nèi)容的簡介。
【編輯推薦】