This article mainly introduces the collection of multiple Ruby Traversal folder code instances, this article summed up 4 pieces of code, small series recommend the last method, because it is very simple and elegant, need friends can refer to the
First, traversing all files under the folder, output file name
The code is 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
The code is 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
The code is 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:workspacepydemofas ', [])
For E in list:
Print E
Result
The code is as follows:
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
Four, concise traversal of the wording
The code is 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