日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python里的os模块_python中os模块再回顾

發布時間:2025/3/21 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python里的os模块_python中os模块再回顾 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

先看下我的文件目錄結構

F:\PYTHON項目\ATM購物車\7月28

在此目錄下的文件如下:

封裝.py

模塊os.sys復習.py

運行當前的文件是模塊os.sys復習.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()就是返回上級目錄的意思,如果傳的參數是個文件,那么就返回當前文件所在目錄,如果傳的參數是個文件目錄,那么就返回這個目錄的上級目錄。

2.獲取當前文件的絕對路徑 os.path.abspath("filename")

import os

d1 = os.path.abspath(__file__)

print(d1)

輸出為:F:\PYTHON項目\ATM購物車\7月28\模塊os.sys復習.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復習.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復習.py')

t2 = os.path.split('F:\\PYTHON項目\ATM購物車\\7月28')

print(t1)

print(t2)

輸出為:('F:\\PYTHON項目\\ATM購物車\\7月28', '模塊os.sys復習.py')

('F:\\PYTHON項目\\ATM購物車', '7月28')

這些列舉的都是基本常用的,當然os模塊還有很多很多,這里就不一一列舉了。

總結

以上是生活随笔為你收集整理的python里的os模块_python中os模块再回顾的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。