python基礎 檔案os模組使用

2021-10-06 16:05:14 字數 2288 閱讀 7850

with open 可自動釋放資源

# stream = open(r'c:\users\lizhu.ding\desktop\aa.txt','wb')

with

open

(r'c:\users\lizhu.ding\desktop\aa.txt'

,'rb'

)as stream:

container = stream.read(

)print

(stream.name)

file

= stream.name

filename =

file

[file

.rfind(

'\\')+

1:]#擷取檔名

#write 如果指定檔案不存在時,會自動建立

os oprating system 作業系統

os:os.getcwd() 獲取當前目錄

os.listdir()瀏覽資料夾

os.mkdir()建立資料夾

os.rmdir()刪除空資料夾

os.remove()刪除檔案

import os

print

(os.path)

print

(os.path.dirname(__file__)

)# 當前檔案路徑

path = os.path.dirname(__file__)

print

(type

(path)

)#以字串格式儲存

path = r'c:\users\xiaoming\desktop\aa.txt'

result = os.path.split(path)

print

(result)

輸出:

儲存在元組中

(

'c:\\users\\xiaoming\\desktop'

,'aa.txt'

)

filename = result[1]

result = os.path.splitext(path)

# 分割檔案與副檔名

print

(result)

(

'c:\\users\\xiaoming\\desktop\\aa'

,'.txt'

)

size = os.path.getsize(path)

print

(size)

# 獲取檔案的大小,單位位元組

os.getcwd() 獲取當前目錄

(result)輸出:

)# 返回指定目錄下的所有檔案和資料夾

print

(all

)# 儲存在列表中os.mkdir

f = os.mkdir(r'c:\ll'

)print

(f)

if

not os.path.exists(r'c:\ll'):

f = os.mkdir(r'c:\ll'

)print

(f)

f = os.rmdir(r'c:\ll'

)#只能刪除空資料夾

f = os.removedirs(r'c:\ll'

)

filelist = os.listdir(path)

forfile

in filelist:

path1 = os.path.join(path,

file

) os.remove(path1)

else

: os.rmdir(path)

python基礎 os模組

對作業系統進行操作的模組 os.walk 遍歷當前資料夾中所有的檔案及資料夾 os.chdir 改變目錄 os.sep 根據不同的平台使用不同的分隔符 os.getcwd 獲取當前路徑目錄 os.listdir 獲取當前路徑下所有的檔案及資料夾 os.mkdir 建立目錄 os.mkdirs 遞迴建...

python基礎 OS模組

os模組主要用來處理檔案和目錄import os1 os.getcwd 檢視當前目錄,模擬pwd print os.getcwd 輸出結果 home idex work2 os.chdir 切換目錄,模擬cd os.chdir r home idex print os.getcwd 輸出結果 hom...

Python基礎(os模組)

os模組主要是和作業系統互動的模組 常見操作os.cpu count 獲取當前作業系統cpu的核心數 os.system command 指定dos命令 os.rename old,new 重新命名檔案 os.remove filepath 刪除檔案 os.mkdir path 建立目錄 os.ma...