本文實例講述了python中os操作文件及文件路徑的方法。分享給大家供大家參考。具體分析如下:
python獲取文件上一級目錄:取文件所在目錄的上一級目錄
代碼如下:os.path.abspath(os.path.join(os.path.dirname('settings.py'),os.path.pardir))
os.path.pardir是父目錄,os.path.abspath是絕對路徑
舉例具體看一下輸出:
代碼如下:print os.path.dirname(os.path.abspath("__file__"))
print os.path.pardir
print os.path.join(os.path.dirname("__file__"),os.path.pardir)
print os.path.abspath(os.path.join(os.path.dirname("__file__"),os.path.pardir))
輸出結果:
G:/work/python
.. #這是兩個點“..”,也就是上級目錄的表示方法
..
G:/work
獲取文件當前路徑: 代碼如下:os.path.dirname(os.path.abspath('__file__'))
python中對文件、文件夾(文件操作函數)的操作需要涉及到os模塊和shutil模塊。
得到當前工作目錄,即當前Python腳本工作的目錄路徑: os.getcwd()
返回指定目錄下的所有文件和目錄名:os.listdir()
函數用來刪除一個文件:os.remove()
刪除多個目錄:os.removedirs(r“c:/python”)
檢驗給出的路徑是否是一個文件:os.path.isfile()
檢驗給出的路徑是否是一個目錄:os.path.isdir()
判斷是否是絕對路徑:os.path.isabs()
檢驗給出的路徑是否真地存:os.path.exists()
返回一個路徑的目錄名和文件名:os.path.split() eg os.path.split('/home/swaroop/byte/code/poem.txt') 結果:('/home/swaroop/byte/code', 'poem.txt')
分離擴展名:os.path.splitext()
獲取路徑名:os.path.dirname()
獲取文件名:os.path.basename()
運行shell命令: os.system()
讀取和設置環境變量:os.getenv() 與os.putenv()
給出當前平臺使用的行終止符:os.linesep Windows使用'/r/n',Linux使用'/n'而Mac使用'/r'
指示你正在使用的平臺:os.name 對于Windows,它是'nt',而對于Linux/Unix用戶,它是'posix'
重命名:os.rename(old, new)
創建多級目錄:os.makedirs(r“c:/python/test”)
創建單個目錄:os.mkdir(“test”)
獲取文件屬性:os.stat(file)
修改文件權限與時間戳:os.chmod(file)
終止當前進程:os.exit()
獲取文件大?。簅s.path.getsize(filename)
目錄操作:
os.mkdir("file") 創建目錄
復制文件:
shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") oldfile只能是文件夾,newfile可以是文件,也可以是目標目錄
復制文件夾:
shutil.copytree("olddir","newdir") olddir和newdir都只能是目錄,且newdir必須不存在
新聞熱點
疑難解答