Ruby:从文件读取+文件类方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ruby:从文件读取+文件类方法相关的知识,希望对你有一定的参考价值。

  1. =begin
  2. 'r' = Read from start (it must exist beforehand)
  3. 'w' = Start a new file, Write from the start but destroys any existing data (very distructive)
  4. 'a' = Append / Write from end
  5. 'r+' = Read and write without being destructive
  6.  
  7.  
  8. #File.new( 'file_name.extension', 'r|w|a|r+|w+|a+' )
  9. file = File.new( 'file_example.txt', 'w' )
  10.  
  11. #You must close to free up the resources
  12. file.close
  13.  
  14. #Open a file, pass a block of instructions, and it will open and close on its own
  15. File.open( 'file_example.txt', 'r') do |file|
  16.   #Read data from the file
  17. end
  18.  
  19. =end
  20.  
  21. file = File.new("file_example.txt", "w")
  22. #Various ways to print to a file
  23. file.puts "Ruby"
  24. file.print "programing "
  25. file.write "is"
  26. file << "fun"
  27. #Close method is required to actually save
  28. file.close
  29.  
  30. File.open("file_example.txt", "r") do |file|
  31. #While there is a new line
  32. while line = file.gets
  33. puts "** " + line.chomp.reverse + " **"
  34. end
  35. end
  36.  
  37. File.open("file_example.txt", "r") do |file|
  38. file.each_line { |line| puts line.upcase }
  39. end
  40.  
  41.  
  42. ### More File class methods ###
  43.  
  44. file = "file_example.txt"
  45.  
  46. #See if this file exists
  47. puts File.exist?(file)
  48. #Is this a file?
  49. puts File.file?(file)
  50. #IS this a directory?
  51. puts File.directory?(file)
  52. #Readable?
  53. puts File.readable?(file)
  54. #Writable?
  55. puts File.writable?(file)
  56. #Executable?
  57. puts File.executable?(file)
  58. #File Size?
  59. puts File.size(file)
  60. #Just get me what's in the ned
  61. full_path = File.expand_path(file)
  62. puts File.basename(full_path)
  63. #Find the extension
  64. puts File.extname(file)
  65. #Last time it was accessed
  66. puts File.atime(file)
  67. #Last modified time
  68. puts File.mtime(file)
  69. #Last status change time. Read/Write/Owner/Group/or Permissions
  70. puts File.ctime(file)

以上是关于Ruby:从文件读取+文件类方法的主要内容,如果未能解决你的问题,请参考以下文章

有没有办法在 Ruby 中读取不同的文件类型? [关闭]

ruby 从文件中读取并解析信息。

在 Ruby 中读取文件的第一行

从 ruby​​ 中的 pdf 文件中获取元数据

在 Ruby 中,您可以对从文件中读取的数据执行字符串插值吗?

使用 Ruby 逐行读取、编辑和写入文本文件