如何在Ruby中创建文件 [英] How to create a file in Ruby

查看:259
本文介绍了如何在Ruby中创建文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个新文件,但事情似乎也没有按我期望的那样工作.这是我尝试过的:

I'm trying to create a new file and things don't seem to be working as I expect them too. Here's what I've tried:

File.new "out.txt"
File.open "out.txt"
File.new "out.txt","w"
File.open "out.txt","w"

根据我在网上阅读的所有内容,所有这些内容都应该可以使用,但是其中每一个都可以给我以下信息:

According to everything I've read online all of those should work but every single one of them gives me this:

ERRNO::ENOENT: No such file or directory - out.txt

这发生在IRB和Ruby脚本中.我想念什么?

This happens from IRB as well as a Ruby script. What am I missing?

推荐答案

使用:

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

您的选择在哪里:

  • r-只读.该文件必须存在.
  • w-创建一个用于写入的空文件.
  • a-附加到文件.如果文件不存在,则创建该文件.
  • r+-打开文件以同时更新读取和写入.该文件必须存在.
  • w+-创建一个用于读取和写入的空文件.
  • a+-打开文件进行读取和附加.如果文件不存在,则创建该文件.
  • 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.

在您的情况下,最好使用'w'.

In your case, 'w' is preferable.

或者您可以拥有:

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

这篇关于如何在Ruby中创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆