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)
4

1 回答 1

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)
于 2013-05-08T07:57:02.393 回答