简体   繁体   中英

How to write a file in specific path in ruby

I want to save my files in specific path.. I have used like this

file_name = gets 
F = open.(Dir.pwd, /data/folder /#{@file_name },w+)

I'm not sure whether the above line is correct or not! Where Dir.pwd tell the directory path followed by my folder path and the file name given.

It should get store the value on the specific path with the specific file name given. Can anyone tell me how to do that.

Your code has multiple errors. Have you ever tried to execute the script?

Your script ends with:

test.rb:7: unknown regexp options - fldr
test.rb:7: syntax error, unexpected end-of-input
    F = open.(Dir.pwd, /data/folder /#{@file_name },w+)

First: You need to define the strings with ' or " :

file_name = gets 
F = open.(Dir.pwd, "/data/folder/#{@file_name}","w+")

Some other errors:

  • You use file_name and later @file_name .
  • The open method belongs to File and needs two parameters.
  • The file is defined as a constant F . I would use a variable.
  • The path must be concatenated. I'd use File.join for it.
  • You don't close the file.

After all these changes you get:

file_name = gets
f = File.open(File.join(Dir.pwd, "/data/folder/#{file_name}"),"w+")
##
f.close

and the error:

  test.rb:29:in `initialize': No such file or directory @ rb_sysopen - C:/Temp/data/folder/sdssd (Errno::ENOENT)

The folder must exist, so you must create it first.

Now the script looks like:

require 'fileutils'
dirname = "data/folder"
file_name = gets.strip
FileUtils.mkdir_p(dirname) unless Dir.exists?(dirname)
f = File.open(File.join(Dir.pwd, dirname, file_name),"w+")
##fill the content
f.close

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