一谢谦、獲取路徑
- 獲取當前路徑
法1:
import os
curent_dir = os.getcwd()
法2:
import os
current_path = os.path.dirname(__file__)
print("當前路徑:" + current_path)
- 獲取(上一級)父級路徑
import os
current_path = os.path.dirname(__file__)
parent_path = os.path.dirname(current_path)
print("上一級路徑:" + parent_path)
二、創(chuàng)建路徑
- 創(chuàng)建文件路徑
import os
if not os.path.dirname('/dir/fileDir'):
os.makedirs( '/dir/fileDir' )
三船侧、刪除路徑(文件夾)和文件
3.1 刪除文件
- 若果存在模型路徑(文件夾savedmodel下有文件)
想要刪除包含有內容的文件夾則必須引入shutil模塊。然后再調用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']
#這里面既有文件也有子目錄