国产探花免费观看_亚洲丰满少妇自慰呻吟_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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 建湖县| 怀化市| 奉节县| 万宁市| 河东区| 高州市| 怀仁县| 黄骅市| 建始县| 科技| 宁津县| 襄樊市| 华安县| 临清市| 四子王旗| 都兰县| 青铜峡市| 万载县| 贵溪市| 红安县| 宣威市| 龙山县| 东乌| 上饶市| 天柱县| 武邑县| 安溪县| 资兴市| 舟山市| 噶尔县| 容城县| 遵化市| 泾川县| 谷城县| 西藏| 长丰县| 商水县| 伊宁市| 隆林| 兴海县| 阜平县|