用Python目錄創建及應用
Python目錄是計算機語言常用的語言,可是很多人還是對其不太了解,覺得它的實際應用語言操作太難,其實如果你了解了Python目錄的操作技能,你對其就有個更深的了解。你如果感興趣的話,就看看下面的文章吧!
和普通文件一樣,關于Python目錄的操作也很容易掌握。首先,列出一個目錄的內容:
- view plaincopy to clipboardprint?
- import os
- for fileName in os.listdir ( '/' ):
- print fileName
- import os
- for fileName in os.listdir ( '/' ):
print fileName正如你所見,這很簡單,用三行代碼就可以完成。
創建目錄也很簡單:
- view plaincopy to clipboardprint?
- import os
- for fileName in os.listdir ( '/' ):
- print fileName
- import os
- for fileName in os.listdir ( '/' ):
刪除剛才創建的Python目錄:也可以創建多級目錄:
- 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' )
如果沒有在創建的文件夾中添加任何東西,就可以一次性將它們全部刪除(即,刪除所列的所有空文件夾):
- 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' )
當需要對一個特定的文件類型進行操作時,我們可以選擇“fnmatch”模塊。以下是顯示“.txt”文件的內容和“.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”
以上就是對關于Python目錄具體操作內容的簡介。
【編輯推薦】