我在一个目录中有385个子文件夹,每个子文件夹包含一个CSV文件和几个pdf文件。我正在尝试找到一种方法来浏览每个子文件夹并将pdf列表写入txt文件。 (我意识到有比Ruby更好的语言,但我是编程的新手,它是我所知道的唯一语言。)
我有完成工作的代码,但我遇到的问题是它列出了子文件夹目录。示例:不是将“document.pdf”写入文本文件,而是编写“subfolder / document.pdf”。
有人可以告诉我如何只写pdf文件名吗?
提前致谢!这是我的代码:
class Account
attr_reader :account_name, :account_acronym, :account_series
attr_accessor :account_directory
def initialize
@account_name = account_name
@account_series = account_series
@account_directory = account_directory
end
#prompts user for account name and record series so it can create the directory
def validation_account
print "What account?"
account_name = gets.chomp
print "What Record Series? "
account_series = gets.chomp
account_directory = "c:/Processed Batches Clone/" + account_name + "/" + account_series + "/Data"
puts account_directory
return account_directory
end
end
processed_batches_dir = Account.new
#changes pwd to account directory
Dir.chdir "#{processed_batches_dir.validation_account}"
# pdf list
processed_docs = []
# iterates through subfolders and creates list
Dir.glob("**/*.pdf") { |file|
processed_docs.push(file)
}
# writes list to .txt file
File.open("processed_batches.txt","w") { |file|
file.puts(processed_docs)
}
答案 0 :(得分:0)
可能有更好的方法,但您可以始终在路径的最后一个斜杠上split
:
Dir.glob('**/*.pdf').each do |file_with_path|
processed_docs.push(file_with_path.split('/').last)
end