Ruby: Dir.glob not returning any files

2019-04-21 12:20发布

I am trying to copy files from one folder into another folder, and then record the names of all the files that were copied into a log file. Both folders are in the same directory and I take that path via the command line. In my program currently that happens through

argument3 = ARGV[2] + "\\"

which successfully becomes 'c:\user\alexander\desktop\'. Then I copy the files on my desktop into a folder already on the desktop with

system "copy #{argument3}*.* #{argument3}TestFolder"

This also successfully completes which I verified from the cmd output and from checking the folder itself. Finally I am trying to save the filenames to a log file with the path 'c:\user\alexander\desktop\log.txt'. I tried to do this by using

logFile = "c:\\user\\alexander\\desktop\\log.txt"
Dir.glob(argument3 + "*.*").each do |fileName|
    File.open(logFile, 'a') {|file| file << "\n" + fileName}
end

This does nothing and leaves my logFile empty. I tried to fix this by changing the File.open option to 'w' instead of 'a' but that still did nothing. Then I thought I must be implementing it incorrectly so I tried just putting

Dir.glob(argument3 + "*.*").each do |fileName|
    puts fileName
end

as a sanity check, but this also outputs nothing. Is what I am trying to accomplish possible? If it is, what am I doing wrong, and if its not is there another way to do this?

Edit 1: Changing the Dir.glob argument to

Dir.glob("*")

is making it write the current directories files to the log. I thought that meant I must have some unseen typo in my argument3 variable but when I did

puts argument3 + "*"

its outputting c:\user\alexander\desktop* I tried concatenating the file path before I passed it as an argument to Dir.glob as

filePath = argument3 + "*"
Dir.glob(argument3 + "*.*").each do |fileName|
    File.open(logFile, 'a') {|file| file << "\n" + fileName}
end

And its still not working as I expected. Is there some trick to passing in the exact file path to Dir.glob? I can't guarantee that the program will always be in the directory it needs to copy from when its run.

3条回答
小情绪 Triste *
2楼-- · 2019-04-21 12:21

Dir.glob doesn't take backslashes. Substitute them for forward slashes, even on Windows:

logFile = "c:\\user\\alexander\\desktop\\log.txt"
Dir.glob(argument3.gsub('\\','/') + "*.*").each do |fileName|
    File.open(logFile, 'a') {|file| file << "\n" + fileName}
end
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-21 12:22

Try one star:

logFile = "c:\\user\\alexander\\desktop\\log.txt"
Dir.glob(argument3 + "*").each do |fileName|
    File.open(logFile, 'a') {|file| file << "\n" + fileName}
end
查看更多
Melony?
4楼-- · 2019-04-21 12:23

Dir.glob doesnt seem to be able to take in a file path, only accept a pattern of files to look for in the current directory. The workaround I have for it is to use Dir.chdir to move to the dir I need, then use Dir.glob(".") which gets the desired output

查看更多
登录 后发表回答