file = 'list.txt'
fileArray = []
list_open = File.open(file, "r")
list_open.each_line { |line|
fileArray.push line
}
fileArray.each { |x| puts x }
fileArray.each { |x| FileUtils.cp x, "/home/user/scripts/" }
lists.txt
的内容只是文件的路径。我想从文件中读取并将其传递给cp
,然后将其复制到/home/user/scripts/
。
当我运行此脚本时,这是我收到的错误:
/usr/local/lib/ruby/2.1/fileutils.rb:1401:in `initialize': No such file or directory @ rb_sysopen - /home/user/test.txt (Errno::ENOENT)
from /usr/local/lib/ruby/2.1/fileutils.rb:1401:in `open'
from /usr/local/lib/ruby/2.1/fileutils.rb:1401:in `copy_file'
from /usr/local/lib/ruby/2.1/fileutils.rb:483:in `copy_file'
from /usr/local/lib/ruby/2.1/fileutils.rb:400:in `block in cp'
from /usr/local/lib/ruby/2.1/fileutils.rb:1579:in `block in fu_each_src_dest'
from /usr/local/lib/ruby/2.1/fileutils.rb:1593:in `fu_each_src_dest0'
from /usr/local/lib/ruby/2.1/fileutils.rb:1577:in `fu_each_src_dest'
from /usr/local/lib/ruby/2.1/fileutils.rb:399:in `cp'
from ./for_Test.rb:12:in `block in <main>'
from ./for_Test.rb:12:in `each'
from ./for_Test.rb:12:in `<main>'
答案 0 :(得分:1)
回想一下,文件中的每一行都必须以换行符("\n"
)结尾。您需要将其删除,String#chomp
:
list_path = "list.txt"
filenames = []
File.open(list_path, "r") do |list|
list.each_line do |line|
filenames.push(line.chomp)
end
end
......或者更简洁:
filenames = File.open(list_path, "r") do |list|
list.each_line.map(&:chomp)
end