Ruby 的 File.open 给出“没有这样的文件或目录 - text.txt (Errno::ENOENT)"错误 [英] Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

查看:78
本文介绍了Ruby 的 File.open 给出“没有这样的文件或目录 - text.txt (Errno::ENOENT)"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Win 7 机器上安装了 Ruby 1.9.2.创建了一个简单的 analyzer.rb 文件.它有这一行:

I installed Ruby 1.9.2 on my Win 7 machine. Created a simple analyzer.rb file. It has this one line:

File.open("text.txt").each {|line| puts line}

当我运行代码时,它给了我这个错误:

When I run the code, it gives me this error:

analyzer.rb:1:in `initialize': No such file or directory - text.txt (Errno::ENOENT)
from analyzer.rb:1:in `open'
from analyzer.rb:1:in `<main>'
Exit code: 1

我不明白.在与 analyzer.rb 文件相同的目录中有一个 text.txt 文件.我还尝试提供文件的绝对路径 C:\Ruby192\text.txt,但没有骰子.我错过了什么?

I don't get it. There is a text.txt file in the same directory as the analyzer.rb file. I also tried feeding the absolute path of the file, C:\Ruby192\text.txt, but no dice. What am I missing?

推荐答案

首先要弄清楚您的当前工作目录是用于运行脚本的目录.
在开头添加这一行:

Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:

放入目录.pwd.

这将告诉您 ruby​​ 在哪个当前工作目录中运行您的脚本.您很可能会发现它不在您认为的位置.然后确保为 Windows 正确指定路径名.请参阅此处的文档如何正确格式化 Windows 的路径名:

This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:

http://www.ruby-doc.org/core/classes/IO.html

然后使用 Dir.chdir 将工作目录更改为 text.txt 所在的位置,或者根据上述 IO 文档中的说明指定文件的绝对路径名.应该这样做...

Then either use Dir.chdir to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...

编辑

添加第三个解决方案,这可能是最方便的解决方案,如果您将文本文件放在脚本文件中:

Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:

Dir.chdir(File.dirname(__FILE__))

这会自动将当前工作目录更改为与运行脚本的 .rb 文件相同的目录.

This will automatically change the current working directory to the same directory as the .rb file that is running the script.

这篇关于Ruby 的 File.open 给出“没有这样的文件或目录 - text.txt (Errno::ENOENT)"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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