python里的os模块_python中os模块再回顾
先看下我的文件目錄結(jié)構(gòu)
F:\PYTHON項目\ATM購物車\7月28
在此目錄下的文件如下:
封裝.py
模塊os.sys復(fù)習.py
運行當前的文件是模塊os.sys復(fù)習.py
1.獲取當前文件所在目錄os.path.dirname("filename")
import os
d1 = os.path.dirname(os.path.dirname(__file__))
print(d1)
輸出為:F:/PYTHON項目/ATM購物車/7月28
另一種方法:
import os
d1 = os.getcwd()
print(d1)
輸出為:F:\PYTHON項目\ATM購物車\7月28
注意:os.path.dirname()就是返回上級目錄的意思,如果傳的參數(shù)是個文件,那么就返回當前文件所在目錄,如果傳的參數(shù)是個文件目錄,那么就返回這個目錄的上級目錄。
2.獲取當前文件的絕對路徑 os.path.abspath("filename")
import os
d1 = os.path.abspath(__file__)
print(d1)
輸出為:F:\PYTHON項目\ATM購物車\7月28\模塊os.sys復(fù)習.py
3.拼接文件目錄os.path.join(path,name)
import os
d1 = os.path.dirname(__file__)
d2 = os.path.join(d1,"cache")
d3 = os.path.join(d1,"cache","hello")
print(d2)
print(d3)
輸出:F:/PYTHON項目/ATM購物車/7月28\cache
F:/PYTHON項目/ATM購物車/7月28\cache\hello
4.獲取上級目錄
import os
d1 = os.path.dirname(__file__)
# 這里的..就是表示上級目錄
d2 = os.path.join(d1,"..")
d3 = os.path.abspath(d2)
print(d1)
print(d2)
print(d3)
輸出為:F:/PYTHON項目/ATM購物車/7月28
F:/PYTHON項目/ATM購物車/7月28\..
F:\PYTHON項目\ATM購物車
5.查看指定目錄下的所有文件os.listdir("dirname")
import os
d1 = os.path.dirname(__file__)
# 他是以列表的形式返回
d2 = os.listdir(d1)
print(d1)
print(d2)
輸出為:F:/PYTHON項目/ATM購物車/7月28
['封裝.py', '模塊os.sys復(fù)習.py']
6.查看是否是個文件os.path.isfile(path)是返回true
import os
print(os.path.isfile(os.path.abspath(__file__)))
輸出為:True
7.查看是否是個目錄os.path.isdir(path)
import os
print(os.path.isdir(os.path.abspath(__file__)))
輸出為:False
8.查看指定的路徑是否存在os.path.exists(path)
import os
b =os.path.exists("F:/PYTHON項目/ATM購物車/7月28")
print(b)
輸出為:True
9.拆分路徑名os.path.split()
import os
t1 = os.path.split('F:\\PYTHON項目\ATM購物車\\7月28\\模塊os.sys復(fù)習.py')
t2 = os.path.split('F:\\PYTHON項目\ATM購物車\\7月28')
print(t1)
print(t2)
輸出為:('F:\\PYTHON項目\\ATM購物車\\7月28', '模塊os.sys復(fù)習.py')
('F:\\PYTHON項目\\ATM購物車', '7月28')
這些列舉的都是基本常用的,當然os模塊還有很多很多,這里就不一一列舉了。
總結(jié)
以上是生活随笔為你收集整理的python里的os模块_python中os模块再回顾的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3.6字典有序_Python
- 下一篇: python需要变量命名规则_和孩子一起