简体   繁体   中英

How can I create a file on my desktop from a Ruby script?

I'm building a webcrawler and I want it to output to a new file that is timestamped. I've completed what I thought would be the more difficult part but I cannot seem to get it to save to the desktop.

Dir.chdir "~/Desktop"
dirname  = "scraper_out"
filename = "#{time}" 
Dir.mkdir(dirname) unless File.exists?(dirname) 
Dir.chdir(dirname)
File.new(filename, "w")

It errors out on the first line

`chdir': No such file or directory @ dir_chdir - ~/Desktop

I've read the documentation on FileUtils, File and cannot seem to find where people change into nested directories from the root.

Edit: I don't think FileUtils understands the ~.

~/ is not recognized by Ruby in this context.

Try:

Dir.chdir ENV['HOME']+"/Desktop"

这可能有助于您在指定目录中创建文件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM