Multiple ruby traversal folder code instances collected, ruby instances
1. traverse all files in the folder and output file names
Copy codeThe 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 ')
2. ruby traversal of folders
Copy codeThe 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
3. How does python traverse a directory and output all file names?
Copy codeThe 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 to ignore some folders:
# 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 codeThe Code is 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
Iv. Simple Traversal
Copy codeThe Code is as follows:
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