How Do Open a File for Writing Only If It Doesn't Already Exist in Ruby

How do open a file for writing only if it doesn't already exist in ruby

After doing some further research, it seems you can use the File::CREAT and File::EXCL mode flags.

filename = 'foo'
File.open(filename, File::WRONLY|File::CREAT|File::EXCL) do |file|
file.write contents
end

In this case, open will raise an exception if the file exists. After running once, this program succeeds without error, creating a file named foo. On the second run, the program emits this:

foo.rb:2:in `initialize': File exists - foo (Errno::EEXIST)
from foo.rb:2:in `open'
from foo.rb:2

From man open:

       O_WRONLY        open for writing only
O_CREAT create file if it does not exist
O_EXCL error if O_CREAT and the file exists

File not being created in Ruby script

Instead of using .write try this instead:

File.open("valid_policies.txt", 'a+') {|f| f.write(policy_number.to_s + "\n") }

How to create a file in Ruby

Use:

File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }

where your options are:

  • r - Read only. The file must exist.
  • w - Create an empty file for writing.
  • a - Append to a file.The file is created if it does not exist.
  • r+ - Open a file for update both reading and writing. The file must exist.
  • w+ - Create an empty file for both reading and writing.
  • a+ - Open a file for reading and appending. The file is created if it does not exist.

In your case, 'w' is preferable.

OR you could have:

out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close

Writing to a new file if it doesn't exist, and appending to a file if it does

It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".

import os
player = 'bob'

filename = player+'.txt'

if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not

highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()

How to write to file in Ruby?

The Ruby File class will give you the ins and outs of ::new and ::open but its parent, the IO class, gets into the depth of #read and #write.

How do I create directory if none exists using File class in Ruby?

You can use FileUtils to recursively create parent directories, if they are not already present:

require 'fileutils'

dirname = File.dirname(some_path)
unless File.directory?(dirname)
FileUtils.mkdir_p(dirname)
end

Edit: Here is a solution using the core libraries only (reimplementing the wheel, not recommended)

dirname = File.dirname(some_path)
tokens = dirname.split(/[\/\\]/) # don't forget the backslash for Windows! And to escape both "\" and "/"

1.upto(tokens.size) do |n|
dir = tokens[0...n]
Dir.mkdir(dir) unless Dir.exist?(dir)
end

How to check for file existence

Check out Pathname and in particular Pathname#exist?.

File and its FileTest module are perhaps simpler/more direct, but I find Pathname a nicer interface in general.



Related Topics



Leave a reply



Submit