python檔案 資料夾操作

2021-10-10 12:50:25 字數 1772 閱讀 9597

區別是glob列出的檔名包含了檔案路徑,即glob.glob括號內的路徑;而os.listdir只會獲取檔名。

import glob

file_list = glob.glob(

'./images/*'

)#要列出所有內容路徑後面必須加*

)#可以指定要遍歷的檔名格式

forfile

in file_list:

print

(file

)

import os

dirs = os.listdir( path )

#返回列表

forfile

in dirs:

print

(file

)

filepath,fullflname = os.path.

split

(file_path)

fname,ext = os.path.splitext(fullflname)
import shutil

shutil.move(src, dst)

將某個資料夾裡面的檔案移動到另乙個資料夾裡面

import shutil

import os

defremove_file

(old_path, new_path)

:print

(old_path)

print

(new_path)

filelist = os.listdir(old_path)

#列出該目錄下的所有檔案,listdir返回的檔案列表是不包含路徑的。

print

(filelist)

forfile

in filelist:

src = os.path.join(old_path,

file

) dst = os.path.join(new_path,

file

)print

('src:'

, src)

print

('dst:'

, dst)

shutil.move(src, dst)

if __name__ ==

'__main__'

: remove_file(r"/data/temp1"

, r"/data/temp2"

)

import shutil

shutil.copy(src, dst)

if

not os.path.exists(

'coco/annotations'):

os.makedirs(

'coco/annotations'

)

import os

print

(os.environ.get(

'cuda_path'

))

os.path.basename()返回path最後的檔名,若path以/或\結尾,那麼就會返回空值。

os.path.basename(path)

python資料夾操作

資料夾示意圖 提取路徑 size.py 提取相對路徑 import os print file 列印當前路徑 abspath os.getcwd 獲取當前路徑 ev os.path.abspath 獲取上一級目錄 rootpath os.path.abspath 獲取道根目錄的路徑 print ab...

python檔案和資料夾操作

python中對檔案 資料夾 檔案操作函式 的操作需要涉及到os模組和shutil模組。得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 返回指定目錄下的所有檔案和目錄名 os.listdir 函式用來刪除乙個檔案 os.remove 刪除多個目錄 os.removedi...

python檔案 資料夾常用操作

1.得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 2.返回指定目錄下的所有檔案和目錄名 os.listdir 3.函式用來刪除乙個檔案 os.remove 4.刪除多個目錄 os.removedirs r c python 5.檢驗給出的路徑是否是乙個檔案 os.pa...