2013-12-17 45 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