but still the file has not updated. Any ideas why? Also, when you want to
do in-place editing of the file, do you have to read the file into an
array first?
This line causes an error since arr hasn’t been initialised at this point
arr = myfile.readlines() #change contents of arr
myfile.rewind()
myfile.print arr
This will put all the elements of arr on one line. If you want each element to
appear on a seperate line then you should use
myfile.puts arr
myfile.close()
aside from those two points the program works as expected.
but still the file has not updated. Any ideas why? Also, when you want to
do in-place editing of the file, do you have to read the file into an
array first?
Hope that’s not too confusing,
– Thomas Adam
Hope that helps
Best Regards
Mark Sparshatt
···
On Tuesday 02 Sep 2003 2:45 pm, Thomas Adam wrote:
This line causes an error since arr hasn’t been initialised at this
point
arr =
or arr = Array.new
arr = myfile.readlines() #change contents of arr
myfile.rewind()
myfile.print arr
This will put all the elements of arr on one line. If you want each
element to
appear on a seperate line then you should use
myfile.puts arr
myfile.close()
aside from those two points the program works as expected.
The program was as an example only to illustrate my question which is
below…
—question—
but still the file has not updated. Any ideas why? Also, when you want
to
do in-place editing of the file, do you have to read the file into an
array first?
—end question—
This line causes an error since arr hasn’t been initialised at this
point
arr =
or arr = Array.new
Actually this line isn’t needed.
What you’re doing is creating an empty array then binding the variable arr to
it. Then with the next line you bind the variable arr to the result of
readlines, discarding the old value of arr.
arr = myfile.readlines() #change contents of arr
myfile.rewind()
myfile.print arr
This will put all the elements of arr on one line. If you want each
element to
appear on a seperate line then you should use
myfile.puts arr
myfile.close()
aside from those two points the program works as expected.
The program was as an example only to illustrate my question which is
below…
—question—
but still the file has not updated. Any ideas why? Also, when you want
to
do in-place editing of the file, do you have to read the file into an
array first?
—end question—
I think that would be the simplest way.
If it’s a large file and you don’t want to read it into memory all at once
then what you could do is read the file in a line at a time, writing the
modified line to a temp file, then copy the tempfile over the origional.
Something like
require “ftools”
require “tempfile”
output = Tempfile.open(“temp”)
File.foreach(“test.txt”) do |line| #process_line
output.puts line
end
output.close
File.cp(output.path, “test.txt”)
would do it.
Best Regards
Mark Sparshatt
···
On Tuesday 02 Sep 2003 3:24 pm, Thomas Adam wrote: