python目錄及文件操作


 版權聲明:本文為博主原創文章,歡迎轉載,並請注明出處。聯系方式:460356155@qq.com

 一、分離路徑

fpath,fname=os.path.split(r'E:\projects\abc\def.png')

'E:\\projects\\abc', 'def.png'

擴展名

os.path.split(r'E:\projects\abc\def.png')[-1].split('.')[-1]

png

fpath,fname=os.path.split(r'E:\projects\abc')

'E:\\projects', 'abc'

二、合成路徑

pa = os.path.join(r'E:\projects\abc', 'def.png')

E:\\projects\\abc\\def.png

pa = os.path.join(r'E:\projects', 'abc', 'def.png')

E:\\projects\\abc\\def.png

 三、判斷目錄/文件是否存在

os.path.exists()

四、目錄創建

os.makedirs(fpath) # 可以一直創建各級目錄
os.mkdir(fpath) # 只能創建最后一級目錄

五、目錄刪除

shutil.rmtree(fpath)  #可以刪除非空目錄

os.rmdir(path)  # 目錄非空時才能被刪除

六、列出目錄下的子目錄和文件

os.listdir(r'E:\projects')  

七、列出目錄下的子目錄

[f for f in os.listdir(file_path) if os.path.isdir(os.path.join(file_path, f))]  #  只有一級目錄名

[os.path.join(file_path, f) for f in os.listdir(file_path) if os.path.isdir(os.path.join(file_path, f))]  #  全路徑

八、列出目錄下的文件

[f for f in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, f))]  #  只有文件名

[os.path.join(file_path, f) for f in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, f))]  #  文件絕對路徑

九、刪除文件

os.remove()

十、列出目錄下的所有子目錄

path = r'E:\soft'
for dirpath, dirnames, filenames in os.walk(path):
    for dirname in dirnames:
        print(os.path.join(dirpath, dirname))

十一、列出目錄下的所有文件

path = r'E:\soft'
for dirpath, dirnames, filenames in os.walk(path):
    for filename in filenames:
        print(os.path.join(dirpath, filename))

十二、遍歷目錄

path = r'E:\soft'
for dirpath, dirnames, filenames in os.walk(path):
    print(dirpath, dirnames, filenames)

# 文件拷貝:

shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件

shutil.copyfile(r'G:\ai_data\1.jpg', r'G:\2.jpg') 

shutil.copy("oldfile","newfile") #oldfile只能是文件,newfile可以是文件,也可以是目標目錄

# 文件夾拷貝:

shutil.copytree("olddir","newdir") #olddir和newdir都只能是目錄,且newdir必須不存在

# 文件、文件夾重命名

os.rename("oldname","newname") #文件或目錄都是使用這條命令

os.rename(r'G:\tf\1.jpg',r'G:\tf\43.jpg')

os.rename(r'G:\t',r'G:\tf')

# 文件、文件夾移動

shutil.move("oldpos","newpos")

shutil.move(r'G:\test',r'G:\tf')

shutil.move(r'G:\tf\4.jpg',r'G:\tf\test')

# 移動的同時改名

shutil.move(r'G:\tf\43.jpg',r'G:\tf\test\5.jpg')

 

# windows 目錄鏈接

mklink /J 鏈接 目標


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM