csv_writing.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/local/bin/ruby -w
  2. # csv_rails_import.rb
  3. #
  4. # Created by James Edward Gray II on 2006-11-05.
  5. # Copyright 2006 Gray Productions. All rights reserved.
  6. require "faster_csv"
  7. CSV_FILE_PATH = File.join(File.dirname(__FILE__), "output.csv")
  8. # writing to a file
  9. FasterCSV.open(CSV_FILE_PATH, "w") do |csv|
  10. csv << %w[first last]
  11. csv << %w[James Gray]
  12. csv << %w[Dana Gray]
  13. end
  14. puts File.read(CSV_FILE_PATH)
  15. # >> first,last
  16. # >> James,Gray
  17. # >> Dana,Gray
  18. # appending to an existing file
  19. FasterCSV.open(CSV_FILE_PATH, "a") do |csv|
  20. csv << %w[Gypsy]
  21. csv << %w[Storm]
  22. end
  23. puts File.read(CSV_FILE_PATH)
  24. # >> first,last
  25. # >> James,Gray
  26. # >> Dana,Gray
  27. # >> Gypsy
  28. # >> Storm
  29. # writing to a string
  30. csv_str = FasterCSV.generate do |csv|
  31. csv << %w[first last]
  32. csv << %w[James Gray]
  33. csv << %w[Dana Gray]
  34. end
  35. puts csv_str
  36. # >> first,last
  37. # >> James,Gray
  38. # >> Dana,Gray
  39. # appending to an existing string
  40. FasterCSV.generate(csv_str) do |csv|
  41. csv << %w[Gypsy]
  42. csv << %w[Storm]
  43. end
  44. puts csv_str
  45. # >> first,last
  46. # >> James,Gray
  47. # >> Dana,Gray
  48. # >> Gypsy
  49. # >> Storm
  50. # changing the output format
  51. csv_str = FasterCSV.generate(:col_sep => "\t") do |csv|
  52. csv << %w[first last]
  53. csv << %w[James Gray]
  54. csv << %w[Dana Gray]
  55. end
  56. puts csv_str
  57. # >> first last
  58. # >> James Gray
  59. # >> Dana Gray