2013-05-08 98 views
3

我想將文本預先添加到現有文件中。此代碼工作得很好,但最後一行似乎從未執行。我可以刪除原始文件,但該文件從來沒有在新的臨時文件回原來的文件名重命名......試圖預先使用紅寶石

我敢肯定它的東西很容易,但是,我不知道爲什麼它不工作。誰能幫忙?

# grab input text 
s = "{query}" 

# create insert value in template with timestamp 
tmp = "#{Time.now.strftime('%Y-%m-%d %I:%M %p')}\n#{s}" 

# path to file you wish to append... 
# folder path must exist, file will be created if it doesn't 
o = File.expand_path("~/Dropbox/Notes/1scratchpad.txt") 
n = File.expand_path("~/Dropbox/Notes/1scratchpad.new.txt") 

# open file in append mode and add the string 
File.open(n, 'w') do |n| 
    n.puts tmp 
    n.puts "\n" 
    File.foreach(o) do |li| 
     n.puts li 
    end 
end 

File.delete(o) 
File.rename(n, o) 
+0

能不能請你'p File.delete(O)'向我們展示了輸出。 – 2013-05-08 05:53:29

+1

這對我來說是寫作的。 Ruby 1.9.3-p392,Mac OS X Server 10.5.8 PPC – Substantial 2013-05-08 05:53:42

+2

追加模式爲'a'' FYI。 – squiguy 2013-05-08 05:57:33

回答

0

試試這個

# grab input text 
s = "{query}" 

# create insert value in template with timestamp 
tmp = "#{Time.now.strftime('%Y-%m-%d %I:%M %p')}\n#{s}" 

# path to file you wish to append... 
# folder path must exist, file will be created if it doesn't 
o = File.expand_path("~/Dropbox/Notes/1scratchpad.txt") 
n = File.expand_path("~/Dropbox/Notes/1scratchpad.new.txt") 

# open file in append mode and add the string 
File.open(n, 'a') do |n| 
    n << tmp 
    n << "\n" 
    n << File.read(o) 
end 


#File.delete(o) 
## Delete is no longer rename would take care of everthing 
File.rename(n, o)