Ruby常用文件操作方法

这篇文章主要介绍了Ruby常用文件操作方法,本文讲解了新建文件、读取文件、删除、重命名文件、目录操作等常用文件操作方法,需要的朋友可以参考下

一、新建文件

复制代码 代码如下:

    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

以上就是Ruby常用文件操作方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 脚本专栏