Posted By

chrisaiv on 11/08/09


Tagged

file ruby


Versions (?)

Ruby: Reading from Files + File Class Methods


 / Published in: 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\n"
  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)

Report this snippet  

You need to login to post a comment.