search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

python讀取資料夾內檔案

python讀取資料夾內檔案

 

會使用python讀取資料夾下所有檔案的情況,通常發生在整批資料需要備份、搬移的時候,因此

下面跟大家分享如何使用python讀取資料夾下的所有檔案 

 

import os

 

# 指定要查詢的路徑

yourPath = '/content/sample_data/'

# 列出指定路徑底下所有檔案(包含資料夾)

allFileList = os.listdir(yourPath)

# 逐一查詢檔案清單

for file in allFileList:

#   這邊也可以視情況,做檔案的操作(複製、讀取...)

#   使用isdir檢查是否為目錄

#   使用join的方式把路徑與檔案名稱串起來(等同filePath+fileName)

  if os.path.isdir(os.path.join(yourPath,file)):

    print("I'm a directory: " + file)

#   使用isfile判斷是否為檔案

  elif os.path.isfile(yourPath+file):

    print(file)

  else:

    print('OH MY GOD !!')

 

# listdir不同的是,listdir只是將指定路徑底下的目錄和檔案列出來

# walk的方式則會將指定路徑底下所有的目錄與檔案都列出來(包含子目錄以及子目錄底下的檔案)

allList = os.walk(yourPath)

# 列出所有子目錄與子目錄底下所有的檔案

for root, dirs, files in allList:

#   列出目前讀取到的路徑

  print("path", root)

#   列出在這個路徑下讀取到的資料夾(第一層讀完才會讀第二層)

  print("directory", dirs)

#   列出在這個路徑下讀取到的所有檔案

  print("file", files)

 

以上就是python讀取資料夾內檔案的方法 

如果覺得對你有幫助的話請幫小弟按個讚吧~

 

 

Python相關文章:

python import 路徑說明

python tuple資料讀取、合併、查詢

python使用matplotlib畫折線圖(Line chart)

Python - list的讀取、增加、刪除、修改方法

python dict資料讀取、新增、修改

python使用matplotlib畫圓餅圖(Pie chart)

pandas Dataframe常用的資料處理方法-上(合併資料、選擇欄位、刪除欄位、刪除列)



熱門推薦

本文由 newaurorapixnetnetblog 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦