2013-12-17 111 views
0

我有一個腳本,通過特定的文件夾梳理,發現所有今天被修改了的文件:寫紅寶石輸出到文件

Dir.glob("/path/to/folder/*/*.txt") do |file| 
    f = File.open(file.strip) 
    lines = f.readlines 
    mod = f.mtime 
    modtime = f.mtime.strftime("%I:%M%p") 
    text = lines.join 
    wordcount = text.split.length 
    project = File.basename(file).gsub(/.txt/, ' ').strip 
    if mod > (Time.now - 86400) 
     found_completed = true 
     entry = "#{modtime} - #{project} - #{wordcount}" 
    end 
    if found_completed == false 
    puts "not today" 
    end 
    if found_completed == true 
    puts "worked on #{entry}" 
    end 
end 

這一切工作正常。但是,我也去寫多行輸出到一個文件。當我將其添加到腳本的末尾(在最後的'結束'之前)它會出現空白:

open('/path/to/newfile.txt', 'w') { |f| 
    f.puts ("#{entry}" + "/n/n") } 

任何幫助,將不勝感激。

回答

1

只要改變變量名fff,並做到:

entry = nil 
if mod > (Time.now - 86400) 
    found_completed = true 
    entry = "#{modtime} - #{project} - #{wordcount}" 
end 
open('/path/to/newfile.txt', 'a+') {|ff| ff.puts entry } 

或:

if mod > (Time.now - 86400) 
    found_completed = true 
    entry = "#{modtime} - #{project} - #{wordcount}" 
    open('/path/to/newfile.txt', 'a+') {|ff| ff.puts entry } 
end 

要打開讀/寫操作,然後使用它的文件,做:

fstore = open '/path/to/newfile.txt', 'a+' 
... 
fstore.puts entry 
... 
fstore.close 
+0

這看起來非常接近。但是,如果我使用建議2,則只有在glob搜索中存在多個肯定的情況下才能獲得最後一個條目。在建議1上,我仍然獲得#{entry}的空白輸出。 – craigeley

+0

更改爲模式'a +' –

+0

我認爲DGM的答案也與此有關。將模式更改爲a +,但是現在我得到的空白行不符合「if」條件。有沒有辦法結束glob循環,仍然通過#{entrytext}?或消除空白行? – craigeley

1

您每次都通過glob循環打開文件,覆蓋文件,並且最後處理的文件產生空白條目?

您可能希望將文件打開時包圍glob,因此只會打開一次,將f.puts行放在現在的位置。

編輯

這是一個小更地道的紅寶石......把它分解成一個類,保留部分小型和孤立的意義,給它的意圖揭示函數名。我相信還有更多工作要做,但我認爲這樣可以更容易閱讀。

class FileInfo 
    def initialize(file) 
    @file = File.open(file) 
    end 

    def wordcount 
    @file.read.scan(/\w/).size 
    end 

    def mtime 
    @file.mtime 
    end 

    def formatted_mtime 
    @file.mtime.strftime("%I:%M%p") 
    end 

    def project 
    File.basename(@file.path).gsub(/.txt/, ' ').strip 
    end 

    def recent? 
    @file.mtime > (Time.now - 86400) 
    end 
end 

open('logfile.txt', 'w') do |log| 
    Dir.glob("/path/to/folder/*/*.txt") do |file| 
    fi = FileInfo.new(file) 
    if fi.recent? 
     log.puts "worked on #{fi.formatted_mtime} - #{fi.project} - #{fi.wordcount}" 
    else 
     log.puts "not today" 
    end 
    end 
end 
+0

好s uggestion。但現在,這會產生一個錯誤:「in write」:封閉流(IOError)「 – craigeley

+0

你包圍了整個循環嗎? – DGM