Ruby 使用::expand_path 创建和打开文件并使用::expand_path 创建目录

标签 ruby file io directory

我刚刚开始使用 Ruby 学习文件 IO,并且有一个关于能够使用::expand_path 指向与我的程序运行位置分开的路径的问题。

这基本上是我希望能够做到的,但不幸的是,这对我不起作用。

require 'openuri'
require 'fileutils'

if File.expand_path.exists?("~/newpathdir/")
        File.expand_path.open("~/newpathdir/log.txt", "a+") {|f| f.write("#{Time.now}       Directory is good.  Returning...") }        #If directory is present, does nothing
        return
    else
        FileUtils.mkdir_p.expand_path("~/newpathdir/")
        File.open("~/newpathdir/log.txt", "a+") {|f| f.write("#{Time.now}       Directory not found.  Creating...") }       #If directory not found, writes to log
    end

def writeLatestToFile
    tweet_file = File.open("~/newpathdir/latest_tweet.txt", "a+")       #Opens file
        if tweet_file       #Checks if file opened correctly
            tweet_file.syswrite("#{@latest_tweet["ID"]}\n#{@latest_tweet["Tweet"]}")        #Appends latest_command information to latest_command.txt
        elsif
            File.open("~/newpathdir/log.txt", 'a+') {|f| f.write("#{Time.now}       Error opening tweet_file.txt") }        #If error in opening file, writes to log
        end
end

非常感谢任何帮助。

最佳答案

这是你想要的吗?

require 'fileutils'

def append(path, message)
  path = File.expand_path path
  FileUtils.mkdir_p File.dirname(path)
  File.open(path, "a+") {|f| f.write "#{message}\n" }
end

def log(path, message)
  append(path, "#{Time.now} #{message}")
end

append('~/newpathdir/latest_tweet', "123456\nLatestTweet")
log('~/newpathdir/log', 'Hello world')

也许您还应该试试 LoggerClass: Logger (Ruby 1.9.3)

require 'logger'
require 'fileutils'

path = File.expand_path '~/newnewpathdir/tweets_logger.log'
FileUtils.mkdir_p File.dirname(path)
log = Logger.new(path)

log.debug('Hello world.')
log.info('Info message.')
log.error('Error message.')

关于Ruby 使用::expand_path 创建和打开文件并使用::expand_path 创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493687/

相关文章:

ruby - 与 String 相比,在 Ruby 中使用 StringIO 有什么优势?

java - 写一个巨大的文件和 Java 堆空间

c++ - 如何使用 C++ 复制目录

Java:删除gz文件偶尔失败

Java读取一个txt文件

c++ - 尝试使用 Win32 线程进行异步 I/O

ruby - OSX Mountain Lion 上的默认 Ruby 版本?还是 1.8.x 或 1.9.x?

Ruby 语言备忘单/海报/引用/概述?

ruby - 谁在 `defer` 中定义了 `deploy.rb` ?

java - 尽管使用 servletContext(),getResourceAsStream 返回 null