收集的多個ruby遍曆檔案夾代碼執行個體

來源:互聯網
上載者:User

   這篇文章主要介紹了收集的多個ruby遍曆檔案夾代碼執行個體,本文總結了4個程式碼片段,小編推薦最後一個方法,因為它很簡潔優雅,需要的朋友可以參考下

  一、遍曆檔案夾下所有檔案,輸出檔案名

   代碼如下:

  def traverse_dir(file_path)

  if File.directory? file_path

  Dir.foreach(file_path) do |file|

  if file !="." and file !=".."

  traverse_dir(file_path+"/"+file)

  end

  end

  else

  puts "File:#{File.basename(file_path)}, Size:#{File.size(file_path)}"

  end

  end

  traverse_dir('D:/apache-tomcat')

  二、ruby遍曆檔案夾

   代碼如下:

  def get_file_list(path)

  Dir.entries(path).each do |sub|

  if sub != '.' && sub != '..'

  if File.directory?("#{path}/#{sub}")

  puts "[#{sub}]"

  get_file_list("#{path}/#{sub}")

  else

  puts " |--#{sub}"

  end

  end

  end

  end

  三、python如何遍曆一個目錄輸出所有檔案名稱

   代碼如下:

  #coding=utf-8

  '''

  Created on 2014-11-14

  @author: Neo

  '''

  import os

  def GetFileList(dir, fileList):

  newDir = dir

  if os.path.isfile(dir):

  fileList.append(dir.decode('gbk'))

  elif os.path.isdir(dir):

  for s in os.listdir(dir):

  #如果需要忽略某些檔案夾,使用以下代碼

  #if s == "xxx":

  #continue

  newDir=os.path.join(dir,s)

  GetFileList(newDir, fileList)

  return fileList

  list = GetFileList('D:workspacePyDemofas', [])

  for e in list:

  print e

  result:

   代碼如下:

  D:workspacePyDemofasfile120141113a.20141113-1100.log

  D:workspacePyDemofasfile120141113a.20141113-1101.log

  D:workspacePyDemofasfile120141113a.20141113-1140.log

  D:workspacePyDemofasfile220141113a.20141113-1100.log

  D:workspacePyDemofasfile220141113a.20141113-1101.log

  D:workspacePyDemofasfile220141113a.20141113-1140.log

  四、簡潔遍曆寫法

   代碼如下:

  import os

  def iterbrowse(path):

  for home, dirs, files in os.walk(path):

  for filename in files:

  yield os.path.join(home, filename)

  for fullname in iterbrowse("/home/bruce"):

  print fullname

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.