一步一步學Ruby(二十): 檔案使用

來源:互聯網
上載者:User
一、 建立檔案
f=File.new(File.join("C:","Test.txt"), "w+")f.puts("I am Jack")f.puts("Hello World")

檔案模式

"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.

"a" :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

二、讀取檔案

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

輸出:

1.白日依山盡

2.黃河入海流

3.欲窮千裡目

4.更上一層樓

三、建立、刪除、重新命名檔案

File.new( "books.txt", "w" )File.rename( "books.txt", "chaps.txt" )File.delete( "chaps.txt" )

三、目錄操作

建立目錄Dir.mkdir("c:/testdir")#刪除目錄Dir.rmdir("c:/testdir")#查詢目錄裡的檔案p Dir.entries(File.join("C:","Ruby")).join(' ')#遍曆目錄Dir.entries(File.join("C:","Ruby")).each {      |e| puts e}

輸出:

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

查看目錄資訊

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 e}...binChangeLog.txtdoclibLICENSE.txtmanMANIFESTmiscREADME.1stReleaseNotes.txtruby.icorubyopt.delrubyw.icosamplesscitesharesrcuninstall.exe=> #irb(main):007:0>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.