close

Python

另外站長打個廣告,最近站長正在嘗試經營遊戲直播平台希望大家能夠幫忙追隨訂閱一下,站長真心感謝~

TWITCH直播https://www.twitch.tv/saioyan

Youtubehttps://www.youtube.com/channel/UCtCeeanvsVdAuqNUyt91GXw/about

[Python]讀取資料夾目錄檔案路徑

關鍵字:資料夾、目錄、檔案、讀取、路徑、for迴圈

我們在讀取多筆資料時通常需要掃描搜尋當下或是指定目錄中的檔案或是資料夾,一筆一筆去搜尋曠日廢時所以以下就來介紹如何一次讀取整個目錄的檔案和資料夾


基礎練習

假設今天我們想要搜尋D槽目錄中的某個資料夾如下圖,有三個資料夾和一個文字檔

image

path先指定目錄位置,dirlist讀取目錄位置後使用for迴圈將指定目錄中的資料夾和檔案清單全部列出來

import os
path = 'D:\\DIR'
dirlist = os.listdir(path)
for i in dirlist:
    print(i)
>>
A
ABC.txt
B
C

進階練習

如果在讀取目錄中的資料夾和檔案的當下想要分別對資料家和檔案做處理可以先用join取得完整的路徑,接著使用isfile(完整路徑)isdir(完整路徑)當作判斷式加入程式碼執行不同的動作

isfile(完整路徑)代表此路徑連結的是檔案類型

isdir(完整路徑)代表此路徑連結的是資料夾類型

import os
from os.path import isfile, isdir, join
path = 'D:\\DIR'
dirlist = os.listdir(path)
for i in dirlist:
    Completepath = join(path,i)
    if isfile(Completepath):
        print('檔案:',i,'路徑:',Completepath)
    if isdir(Completepath):
        print('目錄:',i,'路徑:',Completepath)
>>
目錄: A 路徑: D:\DIR\A
檔案: ABC.txt 路徑: D:\DIR\ABC.txt
目錄: B 路徑: D:\DIR\B
目錄: C 路徑: D:\DIR\C

以上[Python]讀取資料夾目錄檔案路徑介紹到這邊,祝大家學習Python愉快!!!

[Python] Python學習總集

本網站https://kk665403.pixnet.net/內之全部圖文,Saioyan梟夜所有,非經本人同意不得將全部或部分內容轉載於任何形式之媒體
Copyright © 2021 Saioyan. All rights reserved.
版權所有© 2021 Saioyan梟夜

arrow
arrow
    文章標籤
    python pycharm
    全站熱搜

    Saioyan梟夜 發表在 痞客邦 留言(0) 人氣()