Page 1 of 1

File Manipulation Basics

#1 nimajneb  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 11
  • View blog
  • Posts: 116
  • Joined: 04-August 10

Posted 09 December 2010 - 11:42 AM

Ruby makes manipulating files very easy. Here is a quick run through on how to create, open, read, write, close, and delete files.

Creating Files
==============

To create a new file, use the new method with the File class.

File.new("foobar.txt", "w")



New accepts two arguements: the file name and the mode of the file. Acceptable modes to use in Ruby are:

r sets mode to Read only
r+ sets mode to Read/Write only
w sets mode to Write only
w+ sets mode to Write/Read only
a sets mode to Write only with pointer positioned at EoF
a+ sets mode to Read/Write only with pointer positioned at EoF

Opening Files
=============

To open a file you have already created, use the open method with the File class

myfile = File.open("foobar.txt")



You can use the above line of code with the methods listed above as well:

myfile = File.open("foobar.txt", "w+")



Adding the w+ at the end will open this file in Read/Write Only.

Writing and Reading to Files
============================

Make sure you have the file you wish to edit opened. You can check this with the closed? method:

myfile.closed?



This should return false if the file has been opened.

To write a line to your file, use the puts method with the File class:

myfile.puts("This is the first line in my new file")



Running this code again will add the next bit of text to a new line.

myfile.puts("This is the second line in my new file")



To read the file, you need to move the pointer back to the beginning of the file. To do this, use rewind:

myfile.rewind



Now that we are at the top of the file, we can read individual lines with:

myfile.readline



or print the whole document to screen using the each method:

myfile.each (|line| print line)



Closing, Renaming, and Deleting Files
=====================================

Once your done manipulating the file, you may want to close it.

myfile.close



Renaming the file is just as easy:

File.rename("foobar.txt", "newname.txt")



And when you're tired of the file all together, just delete it with:

File.delete("newname.txt")



Is This A Good Question/Topic? 0
  • +

Replies To: File Manipulation Basics

#2 MitkOK  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 32
  • View blog
  • Posts: 403
  • Joined: 09-August 07

Posted 25 December 2010 - 01:42 AM

You should mention that it's better to use open files using the block version to ensure closing it automatically:

File.open("myfile.txt", "r") do |file|
  # do stuff
end

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1