No such file or directory? - ruby

Ruby is giving me this error:
C:/Ruby/new.rb:11:in `read': No such file or directory - m.txt (Errno::ENOENT)
from C:/Ruby/new.rb:11:in `<main>'
But I'm sure that there is such file, Here is my code:
text = File.read("m.txt").split('\n')
text.each do |x|
x.to_i
File.open("m.txt", "w") do |file|
file.gsub(x, x *10)
end
end
The line that is generating this error:
text = File.read("m.txt").split('\n')
I have checked several examples, like this: How can I read a file with Ruby?
And tried things like:
File.open("m.txt", "r+") do |infile|
while (line = infile.gets)
line.to_i.gsub(line, line *10)
end
end
But I'm still getting this error.
What I'm trying to do is: I have some numbers in text file like
12.2
432.3
3.43
.342
...
And I want to multiply each one by 10. Note I'm sure about the file and that it exists.

You have to provide the absolute path:
text = File.read("C:/Ruby/m.txt").split('\n')
since your current directory is not the same as your script's directory.
Alternatively, you should navigate to that specific folder and then run the script.

You can do it this way:
text = File.read("C:/Ruby/m.txt").split('\n')
File.open("C:/Ruby/m.txt", "w") do |file|
text.each do |x|
file.puts x.to_f * 10
end
end

Related

File.write doesn't write

I'm enjoying a very interesting problem where File.write... only works occasionally, i.e., seemingly when it's at the end of the method. For some weird reason this works:
def update(id)
r = HTTParty.get("#{user_api_url}/#{id}?token=#{token}").parsed_response
file_path = "/Users/#{server_user}/server/resources/users/"
File.write("#{file_path}#{id}#{extension(r['user_file_name'])}", open("#{r['user_url']}").read, { mode: 'wb' })
File.write("#{file_path}#{id}_logo#{extension(r['logo_file_name'])}", open("#{r['user_logo_url']}").read, { mode: 'wb' })
end
And this doesn't:
def update(id)
r = HTTParty.get("#{user_api_url}/#{id}?token=#{token}").parsed_response
file_path = "/Users/#{server_user}/server/resources/users/"
r['shared_resources'].map do |key, value|
file = "#{file_path}shared_resources/#{value.split('/')[-1]}"
p "#{timestamp}: Saving #{key} from #{api_server}#{value} into #{file}"
File.write(file, open("#{api_server}#{value}").read, mode: 'wb')
end
File.write("#{file_path}#{id}#{extension(r['user_file_name'])}", open("#{r['user_url']}").read, mode: 'wb')
File.write("#{file_path}#{id}_logo#{extension(r['logo_file_name'])}", open("#{r['user_logo_url']}").read, mode: 'wb')
end
The second method doesn't generate any errors at all, but no files are written. The paths and the URL are both correct. Makes me think I'm not opening or closing something correctly but I don't know what. Any ideas?
UPDATE
Getting this error:
Errno::ENOENT: No such file or directory # rb_sysopen - /Users/user123/server/resources/users/shared_resources/cqap_logo_cmyk-6a82ebd2e336c92188a58cacf26792cf9f43b6d296ae51c2b3fe...
Which is from File.write in the loop.
UPDATE 2
The r['shared_resources'] outputs this:
{\"logo\"=>\"/assets/server/user123-6a82ebd2e336c92188a58cacf26792cf9f43b6d296ae51c2b3fe05a0c1802794.jpg\"}"
But nothing in the loop seems to do anything.
It looks like shared_resources folder does not exist. First snippet writes directly in existing file_path, while second one tries to write into subfolder. Put the following right after you have file_path defined:
Dir.mkdir File.join file_path, 'shared_resources' # unless exists?

Errno::EISDIR in 'initialize' : Is a directory # rb_sysopen - persistent.bak (Errno::EISDIR)

I am iterating through files in a folder to search for specific string.
There is a folder name as persistent.bak. While going through this folder, it is giving error... in 'initialize' : Is a directory # rb_sysopen - persistent.bak (Errno::EISDIR).
Dir.glob("**/*.*") do |file_name|
fileSdfInput = File.open(file_name)
fileSdfInput.each_line do |line|
if ((line.include?"DATE")
#count = #count + 1
end
end
end
your glob Dir.glob("**/*.*") matches the pattern persistent.bak
So inside your loop, you're actually trying to open the folder named persistent.bak as a file, which ruby doesn't appreciate.
Just to convince yourself, try to output the file name, you'll see it.
Simplest workaround :
Dir.glob("**/*.*") do |file|
next if File.directory? file
fileSdfInput = File.open(file)
fileSdfInput.each_line do |line|
if (line.include?"DATE")
#count = #count + 1
end
end
end

In Ruby- Parsing Directory and reading first row of the file

Below is the piece of code that is supposed read the directory and for each file entry prints the first row of the file. The issue is x is not visible so file is not being parsed.
Dir.foreach("C:/fileload/src") do |file_name|
x = file_name
puts x
f = File.open("C:/fileload/src/" +x)
f.readlines[1..1].each do |line|
puts line
end
end
Why are you assigning x to file_name? You can use file_name directly. And if you are only reading the first line of the file, why not try this?
#!/usr/bin/ruby
dir = "C:/fileload/src"
Dir.foreach(dir) do |file_name|
full = File.join(dir, file_name)
if File.file?(full)
f = File.open(full)
puts f.first
f.close
end
end
You should use File.join to safely combine paths in Ruby. I also checked that you are opening a file using the File.file? method.
You have no visibility issue with x. You should be using File::join or Pathname#+ to build your file paths. You should exclude non-files from consideration. You're selecting the second line, not the first with [1..1]. Here's a cleaner correct replacement for your sample code.
dir = "C:/fileload/src"
Dir.foreach(dir).
map { |fn| File.join(dir,fn) }.
select { |fn| File.file?(fn) }.
each { |fn| puts File.readlines(fn).first }

How to open and read files line-by-line from a directory?

I am trying to read file lines from a directory containing about 200 text files, however, I can't get Ruby to read them line-by-line. I did it before, using one text file, not reading them from a directory.
I can get the file names as strings, but I am struggling to open them and read each line.
Here are some of the methods I've tried.
Method 1:
def readdirectory
#filearray = []
Dir.foreach('mydirectory') do |i|
# puts i.class
#filearray.push(i)
#filearray.each do |s|
# #words =IO.readlines('s')
puts s
end#do
# puts #words
end#do
end#readdirectory
Method 2:
def tryread
Dir.foreach('mydir'){
|x| IO.readlines(x)
}
end#tryread
Method 3:
def tryread
Dir.foreach('mydir') do |s|
File.readlines(s).each do |line|
sentence =line.split
end#inner do
end #do
end#tryread
With every attempt to open the string passed by the loop function, I keep getting the error:
Permission denied - . (Errno::EACCES)
sudo ruby reader.rb or whatever your filename is.
Since permissions are process based you can not read files with elevated permissions if the process reading does not have them.
Only solutions are either to run the script with more permissions or call another process which is already running with higher permissions to read for you.
Thanks for all replies,I did a bit of trial and error and got it to work.This is the syntax I used
Dir.entries('lemmatised').each do |s|
if !File.directory?(s)
file = File.open("pathname/#{s}", 'r')
file.each_line do |line|
count+=1
#words<<line.split(/[^a-zA-Z]/)
end # inner do
puts #words
end #if
end #do
Try this one,
#it'll hold the lines
f = []
#here test directory contains all the files,
#write the path as per the your computer,
#mine's as you can see, below
#fetch filenames and keep in sorted order
a = Dir.entries("c:/Users/lordsangram/desktop/test")
#read the files, line by line
Dir.chdir("c:/Users/lordsangram/desktop/test")
#beginning for i = 1, to ignore first two elements of array a,
#which has no associated file names
2.upto(a.length-1) do |i|
File.readlines("#{a[i]}").each do |line|
f.push(line)
end
end
f.each do |l|
puts l
end
#the Tin Man -> you need to avoid processing "." and ".." which are listed in Dir.foreach and give the permission denied error. A simple if should fix all your apporoaches.
Dir.foreach(ARGV[0]) do |f|
if f != "." and f != ".."
# code to process file
# example
# File.open(ARGV[0] + "\\" + f) do |file|
# end
end
end

Strange number conversion while reading a csv file with ruby

i've got a strange problem in ruby on rails
There is a csv file, made with Excel 2003.
5437390264172534;Mark;5
I have a page with upload input and i read the file like this:
file = params[:upload]['datafile']
file.read.split("\n").each do |line|
num,name,type = line.split(";")
logger.debug "row: #{num} #{name} #{type}"
end
etc
So. finally i've got the following:
num = 5437...2534
name = Mark
type = 5
Why num has so strange value?
Also i tried to do like this:
str = file.read
csv = CSV.parse(str)
csv.each do |line|
RAILS_DEFAULT_LOGGER.info "######## #{line.to_yaml}"
end
but again i got
######## ---
- !str:CSV::Cell "5437...2534;Mark;5"
The csv file in win1251 (i can't change file encoding)
ruby file in UTF8
ruby version 1.8.4
rails version 2.0.2
If it indeed has a strange value, it probably has to to do with the code you didn't post. Edit your question, and include the smallest bit of code that will run independently and still produce your questionable output.
split() returns an array of strings. So the first value of your CSV file is a String, not a Bignum. Maybe you need num.to_i, or a test like num.is_a?(Bignum) somewhere in your code.
file = File.open("test.csv", "r")
# Just getting the first line
line = file.gets
num,name,type = line.split(";")
# split() returns an array of String
puts num.class
puts num
# Make num a number
puts num.to_i.class
puts num.to_i
file.close
Running that file here gives me this:
$ ruby test.rb
String
5437390264172534
Bignum
5437390264172534

Resources