溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python中怎么創(chuàng)建目錄

發(fā)布時間:2021-07-05 17:07:32 來源:億速云 閱讀:155 作者:Leah 欄目:編程語言

Python中怎么創(chuàng)建目錄,針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

首先,列出一個目錄的內(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中怎么創(chuàng)建目錄問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI