Using `gets` for file path [duplicate] - ruby

This question already has answers here:
Ruby: String Comparison Issues
(5 answers)
Closed 3 years ago.
I'm writing a script to edit an excel file. I'm testing if it collects information from a user.
require 'rubygems'
require 'win32ole'
print "filpath?"
$filepath = $stdin.gets
print "sheet?"
$sheetname = $stdin.gets
excel = WIN32OLE.new('Excel.Application')
excel.visible = true
workbook = excel.workbooks.Open($filepath)
worksheet = workbook.Worksheets($sheetname)
worksheet.Cells(2,2).Value = 10
workbook.saved = true
workbook.Save
excel.ActiveWorkbook.Close(0)
excel.Quit()
When I put my file path in the script directly, it works fine. It can look up the excel file and edit it normally. However, when I collect it from a gets statement, it gives me this error message:
test.rb:20:in `method_missing': (in OLE method `Open': ) (WIN32OLERuntimeError)
OLE error code:800A03EC in Microsoft Excel
Sorry, we couldn't find C:\filename.xlsx
. Is it possible it was moved, renamed or deleted?
HRESULT error code:0x80020009
Exception occurred.
from test.rb:20:in `<main>'
Not sure what is happening. I would love any help.

The end line character is appended to the file name when you receive it with gets, but probably your file is not named as such. Add .chomp after gets. It is also better to check the existence and the accessibility of the file before passing it to win32ole.

Related

Ruby: Add line in file [duplicate]

This question already has answers here:
What are the Ruby File.open modes and options?
(2 answers)
Closed 6 years ago.
I have a file in which one I want to store some datas.
Using IRB, I can add different lines in the file. However, using a Ruby script writen in a file, I have issues.
I can write a line, it is stored as it should be, but when I re launch the script and re use the method, it overwrites what was in the file instead of adding content at the next line.
def create_new_account
puts "Set the account's name"
#account_name = gets
puts "New account's name: #{#account_name}
open("accounts.txt","w+") do |account_file|
account_file.write "ac;#{#account_name}\n"
end
end
I had a look to the different parameters of the method open, but seems like it's not there.
Moreover, I tried puts instead of write, but there is no difference, always the same problem.
Could someone help me understand what is wrong with the code?
Thanks
Try opening the file in append mode like so
open('accounts.txt', 'a+')
otherwise the file is opened so as to overwrite the existing data.
"a" - Write-only, each write call appends data at end of file.
Creates a new file for writing if file does not exist.

How to write a file with ruby? [duplicate]

This question already has answers here:
How to write to file in Ruby?
(7 answers)
Closed 7 years ago.
I want to create a temp file:
def create_file
FileUtils.mkdir_p('/var/log/my_app')
tmp_file = '/var/log/my_app/tmp_file'
File.open(tmp_file, 'w') do |file|
file.write 'test'
end
end
Here I am sure that the /var/log/my_app path exists. But after I run this method, I can't find a file named tmp_file under that path.
And there wasn't any error, too.
I think you would do better using Ruby's TempFile class and perhaps even Ruby's temp dir as suggested in this article: Quick tips for doing IO with Ruby.
I think you will find the article helpful. I believe it will make your approach easier - especially regarding deleting the file once you're done with it.
I don't see any error in your code. If you don't get any exception, the file must have been created, if this function has been executed.
I suggest that you make a test at the end of create_file:
if File.file?
puts "File has been created"
else
fail "File is not there!"
end
If you see "File has been created", but the file is still missing, something must have erased it before you had time to check its presence. If you see "File is not there!", something weird is going on and I would call an exorcist. If you don't see any message, it means that your function has not been executed.

Reading Files in Ruby

So, I'm relatively new to programming, and I have started working with ruby. I am going through "Learn how to code the hard way: Ruby" and I am on exercise 15; the beginning of file reading. I have copied the code they provided word for word, literally copy and pasted it to make sure, but I am getting the same error. I've googled the error, but to no avail. I have the .rb file in the same directory as the .txt file I'm trying to read. Here is my code.
filename = ARGV.first
prompt = "> "
txt = File.open(filename)
puts "Here's your file: #{filename}"
puts txt.read()
puts "I'll also ask you to type it again:"
print prompt
file_again = STDIN.gets.chomp()
txt_again = File.open(file_again)
puts txt_again.read()
The error I keep getting it this:
ex15.rb:19:in 'initialize': No such file of directory - ex15.txt <Errno::ENOENT>
from ex15.rb:4:in 'open'
from ex15.rb:4:in '<main>'
command to run it:
ruby ex15.rb ex15.txt
Any help is appreciated. Thanks
When you don't specify the mode argument for File.open(), the default is 'r', which stands for read. And to read a file, it has to exist already. The error message is telling you that there is no file named 'ex15.txt' in the current directory for ruby to read.
To get rid of the error, create a file called ex15.txt in the current directory, and type 'hello world' in the file.

Sinatra File deleter

I am using sinatra,ruby and MongoDB to export a CSV file from the MongoDB. I am able to create the CSV file and export it.
I delete the file after exporting it.
But it gets deleted only after I exit sinatra.
Can anybody explain why is this?
Suppose a file abc****.csv is created.
I am deleting this file using
file_path = '/home/Test_app';
file = Tempfile.new([##uname,'.csv'],file_path);
file_name = file.path();
puts file_name # gives /home/Test_app/xyz****.csv
send_file(file_name, :disposition => 'attachment', :filename =>File.basename(file_name));
File.delete(file_name);
File.unlink(file_name);
But it gets deleted only after I exit sinatra server. Can anyone explain please?
Your never call file.close, meaning the file will be kept open and therefore not deleted until your application exits.
Try following the suggestion given in the Tempfile documentation:
file = Tempfile.new('foo')
begin
...do something with file...
ensure
file.close
file.unlink # deletes the temp file
end
This will make sure the file is properly closed and deleted even in the event of exceptions being raised in the code between begin and ensure.
Perhaps this is a large file; since the HTTP connection does not close until the streaming is complete, the code after send_file is not getting executed. That might be a valid reason. Have you checked if the entire file is being downloaded to the client? If that is not the case, try it out with a smaller file. I'm assuming you've implemented (but haven't written it here) the code for the data getting written into the file_name from MongoDB.

ruby parseexecel gem - array not implemented

I am trying to work with two worksheets at the same time.
So I have code
require 'parseexcel'
#Open the excel file passed in from the commandline
workbook = Spreadsheet::ParseExcel.parse(ARGV[0])
workbook2 = Spreadsheet::ParseExcel.parse(ARGV[1])
#Get the first worksheet
worksheet = workbook.worksheet(0)
worksheet2 = workbook2.worksheet(0)
However, when I run this code I get an error: array is not implemented
This error goes away when I comment out line:
workbook2 = Spreadsheet::ParseExcel.parse(ARGV[1])
Why is this happeneing?
Way I am running script is: ruby -rubygems traverse.rb excel.xls so.xls
i fixed it by copy pasting so.xls in excel.xls as a different workbook. then just accessed it by workbook.worksheet(1) that worked

Resources