2016-06-15 76 views
0

我在一個目錄中有385個子文件夾,每個子文件夾都包含一個CSV文件以及幾個pdf文件。我試圖找到一種方法來瀏覽每個子文件夾,並將pdf的列表寫入一個txt文件。 (我知道有比Ruby更好的語言來做這件事,但我是編程新手,而且它是我唯一知道的語言。)Ruby - 將子文件夾的文件名寫入txt文件

我有代碼完成工作,但問題是我運行到它是否也列出了子文件夾目錄。示例:不是將「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

這很有趣,關於Ruby您的評論。我已經編程了數十年,至少使用了十幾種語言,我會推薦任何新的程序員以Ruby開始!這是我最喜歡的。 –

回答

0

有可能是一個更好的辦法,但你總是split通路上的最後一個斜線:

Dir.glob('**/*.pdf').each do |file_with_path| 
    processed_docs.push(file_with_path.split('/').last) 
end 
相關問題