开发者

Removing "." and ".." in work with directories

开发者 https://www.devze.com 2023-03-30 15:37 出处:网络
I want to write a program that get from user a path and then go to that directory and all of subdirectories recurcively and collect all txt files. but \".\" and \"..\" bother me when I am iterating di

I want to write a program that get from user a path and then go to that directory and all of subdirectories recurcively and collect all txt files. but "." and ".." bother me when I am iterating directories recurcively. please help me to eradicating this problem. th开发者_开发百科is is my code :

def detect_files(path)
            Dir.foreach(path) do |i|
        if (i != "." or i !="..")
            if (File.directory?(i))
                detect_files(i)
            end
            if (i.reverse.start_with?("txt."))
                @files[i]=[]
            end
        end
    end

end


The condition should be :

if (i != "." and i != "..")
  • If i="." then i != "." will be false making the condition false, and "." will not be processed
  • If i=".." then i != "." will be true but i != ".." will be false, making the condition false and ".." will not be processed.
  • If i has any other values, then both side of and will be true and the body of if will be executed.


Dir.foreach(path) do |i|
  next if %w(. ..).include?(i)
  # rest of your code
end

Your current version has a wrong condition for the if: you want (i != '.' AND i != '..').


all_txt_files = Dir['**/*.txt']


You could try just doing something like this

def detect_files(path)
  p1 = File.join(path, '**', '*.txt')
  @files = Dir[p1]
 end


Try like this:

Dir.foreach('/path/to/dir') do |item|
  next if item == '.' or item == '..'
  # do work on real items
end

OR

Dir.glob('/path/to/dir/*.rb') do |rb_file|
  # do work on files ending in .rb in the desired directory
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号