Ruby:从文件读取+文件类方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ruby:从文件读取+文件类方法相关的知识,希望对你有一定的参考价值。
=begin 'r' = Read from start (it must exist beforehand) 'w' = Start a new file, Write from the start but destroys any existing data (very distructive) 'a' = Append / Write from end 'r+' = Read and write without being destructive #File.new( 'file_name.extension', 'r|w|a|r+|w+|a+' ) file = File.new( 'file_example.txt', 'w' ) #You must close to free up the resources file.close #Open a file, pass a block of instructions, and it will open and close on its own File.open( 'file_example.txt', 'r') do |file| #Read data from the file end =end file = File.new("file_example.txt", "w") #Various ways to print to a file file.puts "Ruby" file.print "programing " file.write "is" file << "fun" #Close method is required to actually save file.close File.open("file_example.txt", "r") do |file| #While there is a new line while line = file.gets puts "** " + line.chomp.reverse + " **" end end File.open("file_example.txt", "r") do |file| file.each_line { |line| puts line.upcase } end ### More File class methods ### file = "file_example.txt" #See if this file exists puts File.exist?(file) #Is this a file? puts File.file?(file) #IS this a directory? puts File.directory?(file) #Readable? puts File.readable?(file) #Writable? puts File.writable?(file) #Executable? puts File.executable?(file) #File Size? puts File.size(file) #Just get me what's in the ned full_path = File.expand_path(file) puts File.basename(full_path) #Find the extension puts File.extname(file) #Last time it was accessed puts File.atime(file) #Last modified time puts File.mtime(file) #Last status change time. Read/Write/Owner/Group/or Permissions puts File.ctime(file)
以上是关于Ruby:从文件读取+文件类方法的主要内容,如果未能解决你的问题,请参考以下文章