Collection of multiple Ruby Traversal folder code instances _ruby topics

Source: Internet
Author: User

First, traversing all files under the folder, output file name

Copy Code code as follows:

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 ')

Second, Ruby Traverse folder

Copy Code code as follows:

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

Three, Python how to traverse a directory output all file names

Copy Code code as follows:

#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):
#如果需要忽略某些文件夹, use the following code
#if s = = "xxx":
#continue
Newdir=os.path.join (Dir,s)
Getfilelist (Newdir, FileList)
return filelist

List = getfilelist (' D:\\workspace\\pydemo\\fas ', [])
For E in list:
Print E

Result

Copy Code code as follows:

D:\workspace\PyDemo\fas\file1\20141113\a.20141113-1100.log
D:\workspace\PyDemo\fas\file1\20141113\a.20141113-1101.log
D:\workspace\PyDemo\fas\file1\20141113\a.20141113-1140.log
D:\workspace\PyDemo\fas\file2\20141113\a.20141113-1100.log
D:\workspace\PyDemo\fas\file2\20141113\a.20141113-1101.log
D:\workspace\PyDemo\fas\file2\20141113\a.20141113-1140.log

Four, concise traversal of the wording

Copy Code code as follows:

Import OS

def iterbrowse (path):
For home, dirs, the files in Os.walk (path):
For filename in Files:
Yield Os.path.join (home, filename)


For FullName in Iterbrowse ("/home/bruce"):
Print FullName

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.