3

So I have this program that works with passing around a string (this string is the path of the file it is supposed to read)

Now I have a method that has to open that file. change the text with Gsub and than output that file again (The original file can't be edited) but I need to eventually output that changed file

this is the method i'm using to change my file (simplified)

def self.changeFile(myfile)
myfile = @path

doc = File.open(myfile)
text = doc.read

text.gsub!("change" , "changed")

return text

the problem with this is I get the entire file as string returned. My other methods work with the input of a "string" pathname

So my question is is there anyway I can write my text to the file I changed in the memory, so without actually changing the original file?

I was thinking about using "Tempfile" or "StringIO" but I don't know if this is the right thing to go about

All Help is appreciated

  • Do you want to create another file with changed text from original file? If so do you want to make it temp file or an ordinary file? – Maxim Pontyushenko Apr 08 '16 at 10:36
  • @Maxim Pontyushenko Yes I want to create a file with the total new file (the one that is changed) but i don't want to WRITE – FroggyFreshh Apr 08 '16 at 12:20
  • *My other methods work with the input of a "string" pathname*--That rules out StringIO because a StringIO does not have a pathname. *but i don't want to WRITE*--To create a file, you have to write to the file. Tempfile just creates a name for the file that won't clash with any existing filenames. If you want to delete the Tempfile after you are done making all your alterations and have printed out the file, then that would be the way to go. Otherwise, you could create a new file with the same name as the original file plus something like "altered" added to the end of the filename. But .... – 7stud Apr 08 '16 at 12:55
  • ...that could end up overwriting an existing file. To avoid that, you could create a new directory and add the new files to it. – 7stud Apr 08 '16 at 12:58

1 Answers1

1

You can use temple for this:

def self.changeFile(myfile)
  myfile = @path
  tempfile = Tempfile.new("changed")
  tempfile << File.open(myfile).read.gsub("change" , "changed")
  tempfile.close
  tempfile.path
end
Maxim Pontyushenko
  • 2,983
  • 2
  • 25
  • 36