国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Ruby常用文件操作方法

2019-10-26 19:26:54
字體:
來源:轉載
供稿:網友

一、新建文件
代碼如下:
    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

三、新建、刪除、重命名文件
代碼如下:
    File.new( "books.txt", "w" )
    File.rename( "books.txt", "chaps.txt" )
    File.delete( "chaps.txt" )

四、目錄操作
1     創建目錄
代碼如下:
    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
    }

1、ARGV and ARGF
代碼如下:
ARGV
    ARGV << "cnblogslink.txt"
    #The gets method is a Kernel method that gets lines from ARGV
    print while gets
    p ARGV.class

ARGF
    while line = ARGF.gets
     print line
    end

2、文件信息查詢
代碼如下:
    #文件是否存在
    p File::exists?( "cnblogslink.txt" ) # => true
    #是否是文件
    p File.file?( "cnblogslink.txt" ) # => true
    #是否是目錄
    p File::directory?( "c:/ruby" ) # => true
    p File::directory?( "cnblogslink.txt" ) # => false
    #文件權限
    p File.readable?( "cnblogslink.txt" ) # => true
    p File.writable?( "cnblogslink.txt" ) # => true

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 兰溪市| 雷州市| 固原市| 陇南市| 温宿县| 濮阳县| 泸州市| 西峡县| 广宗县| 鄂尔多斯市| 桦南县| 格尔木市| 南靖县| 凤山县| 顺义区| 波密县| 类乌齐县| 通州区| 仁寿县| 柯坪县| 惠东县| 义乌市| 皋兰县| 定陶县| 彰化县| 绥阳县| 正蓝旗| 卢龙县| 清徐县| 东兰县| 江油市| 拜泉县| 曲松县| 吉隆县| 铜鼓县| 吉林市| 宿松县| 邮箱| 云霄县| 文成县| 菏泽市|