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
Add Current Time Before Log Message
Which Http Web Server How to Use to Debug Ruby Code Using Rubymine 3.0.1
How to Export a Rails Model to JSON Schema
How to Find Out the Starting Point for Each Match in Ruby
Is There a Shorthand If (Without Else) Statement in Ruby on Rails
Why Are My Thread Variables Intermittent in Rails
Approach for Installing System Service Implemented as Ruby Gem
Sending Http Post Request in Ruby by Net::Http
Is There a Definitive Reference Document for Ruby Syntax
Hash Remove All Except Specific Keys
Working with a Large Data Object Between Ruby Processes
Rails Elasticsearch Aggregation
Sass: Dealing with The Ie 4095 Selectors Per Stylesheet Restriction
Rounding a Float to the Nearest Integer in Ruby