Step by step to learn Ruby (20): File Usage

Source: Internet
Author: User
I, Create a file
 
F = file. new (file. join ("C:", "test.txt"), "W +") F. puts ("I am Jack") F. puts ("Hello World ")

File Mode

"R": Read-Only. Starts at beginning of file (default mode ).

"R +": Read-write. Starts at beginning of file.

"W": Write-only. truncates existing file to zero length or creates a new file for writing.

"W +": Read-write. truncates existing file to zero length or creates a new file for reading and writing.

"": Write-only. Starts at end of file if file exists; otherwise, creates a new file for writing.

"A +": Read-write. Starts at end of file if file exists; otherwise, creates a new file for reading and writing.

"B":( DOS/Windows only.) binary file mode. may appear with any of the key letters listed above

Ii. Reading files

 
File = file. open (file. join ("C:", "test.txt"), "R") file. each {| Line | print "# {file. lineno }. ", line} file. close

Output:

1. Complete the rest of the mountains on the day

2. Yellow River Current

3. Thousands of miles away

4. Next floor

3. Create, delete, and rename an object

 
File. New ("books.txt", "W") file. Rename ("books.txt", "chaps.txt") file. Delete ("chaps.txt ")

Iii. Directory operations

 
Create directory dir. mkdir ("C:/testdir") # Delete the directory dir. rmdir ("C:/testdir") # query the files in the directory P dir. entries (file. join ("C:", "Ruby ")). join ('') # traverse the directory dir. entries (file. join ("C:", "Ruby ")). each {| E | puts e}

Output:

 
"C:/studyruby" "C:/ruby"

View directory information

 
D: \ study \ rubysample> irbirb (main): 001: 0> dir = dir. open (file. join ("C:", "Ruby") = ># IRB (main): 002: 0> dir. path => "C:/ruby" IRB (main): 003: 0> dir. tell => 0irb (main): 004: 0> dir. read => ". "IRB (main): 005: 0> dir. rewind => # IRB (main): 006: 0> dir. each {| E | puts outputs ==># IRB (main): 007: 0>
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.