首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用::expand_path创建并打开文件,用::expand_path创建目录

用::expand_path创建并打开文件,用::expand_path创建目录
EN

Stack Overflow用户
提问于 2013-05-11 04:15:19
回答 1查看 1.8K关注 0票数 2

我刚刚开始使用Ruby学习文件IO,并遇到了一个问题,即如何使用::expand_path来指向与我的程序运行位置不同的路径。

这是我本质上想要做的事情,但不幸的是,这对我不起作用。

代码语言:javascript
复制
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

任何帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-11 05:55:00

这是你想要的吗?

代码语言:javascript
复制
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')

也许你也应该试试Logger类:记录器(Ruby1.9.3)

代码语言:javascript
复制
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.')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16493687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档