0

I am trying to open a non existent file and write to it, however when I run the script, no file is being created.

Here is the line of code

File.open("valid_policies.txt", 'a+').write(policy_number.to_s + "\n")
7
  • What does return this call? Commented Jul 16, 2015 at 16:39
  • Is an error thrown? Does it run but nothing happens? Commented Jul 16, 2015 at 16:51
  • @jkeuhlen it runs but nothing happens Commented Jul 16, 2015 at 16:52
  • And you definitely have permissions to write to the directory you run your script from correct? I added an alternative way to do the writes, see if that makes any difference. Commented Jul 16, 2015 at 17:21
  • I need to check if I have permissions, right now the revised way that you posted is not working either. Commented Jul 16, 2015 at 17:25

2 Answers 2

3

Instead of using .write try this instead:

File.open("valid_policies.txt", 'a+') {|f| f.write(policy_number.to_s + "\n") }
Sign up to request clarification or add additional context in comments.

Comments

0

You're using:

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

That's a non-block form of open which doesn't automatically close the file. That means the data is most likely not being written to the file but is sitting in the IO buffer waiting to be flushed/synced. You could add a close but that only propagates non-idiomatic code.

Instead you can use:

File.write("valid_policies.txt", policy_number.to_s + "\n")

File.write automatically creates then writes to the file then closes it. It will overwrite existing files though.

If you aren't sure whether the file exists and want to create it if it doesn't, or append to it, then you use File.open with the a mode instead of a+. From the mode documentation:

"a" Write-only, each write call appends data at end of file. Creates a new file for writing if file does not exist.

Using a+ will work but it unnecessarily opens the file for reading also. Don't do that unless you're sure that's what you have to do.

If I needed to append I'd use:

File.open('valid_policies.txt', 'a') do |fa|
  fa.puts policy_number
end

That's idiomatic Ruby. puts will automatically "stringify" policy_number if it has a to_s method, which it should have since you're already calling it, and it'll also automatically add the trailing "\n" if it doesn't exist at the end of the string. Also, using the block form of open will automatically close the file when the block exists, which is smart house-keeping.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.