python獲取、創(chuàng)建、刪除文件(夾)

一、獲取路徑

  • 獲取當(dāng)前路徑
    法1:
   import os
   curent_dir = os.getcwd()

法2:

     import os
      current_path = os.path.dirname(__file__)
       print("當(dāng)前路徑:" + current_path)
  • 獲取(上一級(jí))父級(jí)路徑
 import os
  current_path = os.path.dirname(__file__)
  parent_path = os.path.dirname(current_path)
   print("上一級(jí)路徑:" + parent_path)

二、創(chuàng)建路徑

  • 創(chuàng)建文件路徑
  import os
  if not os.path.dirname('/dir/fileDir'):
      os.makedirs( '/dir/fileDir' )

三、刪除路徑(文件夾)和文件

3.1 刪除文件

  • 若果存在模型路徑(文件夾savedmodel下有文件)
    想要?jiǎng)h除包含有內(nèi)容的文件夾則必須引入shutil模塊。然后再調(diào)用shutil
    模塊的rmtree方法便可以刪除文件夾了唷。
    import shutil
    if os.path.exists('/base_dir/savedmodel/'):
        shutil.rmtree('/base_dir/savedmodel/')
  • 若果存在模型路徑(文件夾savedmodel下沒有文件)
    Python中用來刪除文件夾則是用到os中的rmdir(只可以刪除空滴文件夾)。
    import os
    if os.path.exists( '/base_dir/savedmodel/'):
        os.rmdir('/base_dir/savedmodel/')

3.2 刪除文件

import os
if os.file.exists( 'filename'):
    os.remove('filename')

四、得到目錄下所有文件名數(shù)組:

import os
filelist=os.listdir('/dir/')

eg:
L = os.listdir( "/root/123" )
print L
['test.txt', 'test.py','python']
#這里面既有文件也有子目錄
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容