Ruby File Operations

Source: Internet
Author: User

Read an object and print it out:

 
Lines = file. open ('dom. js '). readlinesputs "=================================" lines. each {| Line | puts (line )}

Or:

 
File. Open ("dom. js") Do | file | while line = file. Gets puts line endend

The latter ensures that the file is closed after it is used up.

Append content to the target file:

 
File = file. Open ("dom. js", "A") file. Puts "// This is new content." file. Close

But sometimes this may not add Chinese content, reported "invalid multibyte char (US-ASCII)" error, we will add such a comment on the top of the current script, it will be okay, that is

 
# Coding: UTF-8 file = file. Open ("dom. js", "A") file. Puts "// This is the newly appended content." file. Close

Create a new file and add content to it.

 # Coding: UTF-8 file = file. new ("new_file.js", "W"); file 

file rename:

 # Coding: UTF-8 file. rename ("new_file.js", "New. JS ") 

file rename:

# coding: UTF-8 file. rename ("new_file.js", "New. JS ") # original file name, new file name 

delete file

 # Coding: UTF-8 file. delete ("New. JS ") # original file name 

directory operation:

 # Coding: UTF-8 dir. mkdir ("new") # create a new folder dir. rmdir ("new") # delete a specified folder 

copy an object to the target Folder:

 require 'fileutils' fileutils. CP 'new. js', 'new' 

move a file to the target:

 require 'fileutils' fileutils. MV 'new. js', 'new' 

http://www.kuqin.com/rubycndocument/man/addlib/fileutils.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.