How to save a hash into a CSV
Try this:
require 'csv'
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
CSV.open("data.csv", "wb") {|csv| h.to_a.each {|elem| csv << elem} }
Will result:
1.9.2-p290:~$ cat data.csv
dog,canine
cat,feline
donkey,asinine
(Ruby) How to convert a nested hash into a csv file
I would do something like this:
require 'csv'
CSV.open('the_file.csv', 'w') do |csv|
hash.each do |id, attributes|
csv << [id, *attributes.values_at(:price, :brand)]
end
end
How to add an array of hashes into a csv file?
You can append to an existing file by using mode: 'a'
: (see open modes)
File.write("#{file_name}.csv", s, mode: 'a')
To write the headers only on the first run, you could check whether the file exists. In addition, you should use a fixed header and fetch the hash values in that specific order, e.g.:
CSV.generate do |csv|
csv << %w[Name Age Country] unless File.exist?("#{file_name}.csv")
hash.each do |x|
csv << x.values_at(:Name, :Age, :Country)
end
end
File.write("#{file_name}.csv", s, mode: 'a')
There's also CSV.open
which creates the file for you:
CSV.open("#{file_name}.csv", 'a') do |csv|
csv << %w[Name Age Country] if csv.stat.zero?
hash.each do |x|
csv << x.values_at(:Name, :Age, :Country)
end
end
Since the file will always exist when the block gets executed, the header check needs to be changed: csv.stat
returns the file's File::Stat
and zero?
determines whether the file is empty.
How to save hash values into a CSV
The join method that @joelparkerhenderson talks about just takes the two array value and joins them togheter.
You can use flatten
to separate and create a new array like this:
# Open the CSV for writing
CSV.open("info.csv", "wb") do |csv|
# Write the entire row all at once
csv << @infodata.values.flatten
end
Read more at: http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-flatten
convert array of hashes to csv file
Try this:
CSV.open("data.csv", "wb") do |csv|
@data.each do |hash|
csv << hash.values
end
end
If you want the first line of the CSV to contain the keys of the hash (a header row), simply do:
CSV.open("data.csv", "wb") do |csv|
csv << @data.first.keys # adds the attributes name on the first line
@data.each do |hash|
csv << hash.values
end
end
Please read the comment of @cgenco below: He wrote a monkey patch for the Array class.
Creating a CSV from a hash
You need to define this method as an instance method of the class Array.
class Array
def to_csv(csv_filename="hash.csv")
require 'csv'
# Get all unique keys into an array:
keys = self.flat_map(&:keys).uniq
CSV.open(csv_filename, "wb") do |csv|
csv << keys
self.each do |hash|
# fetch values at keys location, inserting null if not found.
csv << hash.values_at(*keys)
end
end
end
end
[{ :a=>1, :b=>2 }, { :c=>3 }].to_csv
#=> [{:a=>1, :b=>2}, {:c=>3}]
Let's see what was written.
CSV.read("hash.csv")
#=> [["a", "b", "c"], ["1", "2", nil], [nil, nil, "3"]]
I infer this is an array method from the code fragment
self.flat_map(&:keys)
As the mapping is to keys, it suggests that the reiceiver is an array of hashes.(That expression could have been written flat_map(&:keys)
.)
This method does not appear to meet your requirements.
You could save the keys and values thusly:
CSV.open("hash.csv", "wb") do |csv|
arr.each do |h|
csv << h
end
end
#=> [["a", "b", "c"], [1, 2, 3], [4, 5, 6]]
CSV.read("hash.csv")
#=> [["a", "b", "c"], [1, 2, 3], [4, 5, 6]]
How could i save all the hashes generated from jpg images into a csv file and not only the last one?
Here, you're overwriting your list_rows
variable for every step in the loop. You should append to the list instead, and then write the content of the list to your csv.
import imagehash
from PIL import Image
import glob
import numpy as np
image_list = []
list_rows = []
for filename in glob.glob('/home/folder/*.jpg'):
im = Image.open(filename)
image_list.append(im)
img_hash = imagehash.average_hash(im)
print(img_hash)
list_rows.append([img_hash])
np.savetxt("numpy_test.csv", list_rows, delimiter=",", fmt='% s')
PS: Try not to override builtin (like hash) that may be dangerous !
Save hash in the csv ruby
CSV.open("users.csv", "a") {|csv|
csv << users.values
}
I think, you need this. If users
hash will contains other data - csv will take it to
Related Topics
How to Convert a Ruby Hash So That All of Its Keys Are Symbols
How to Install Jekyll on Osx 10.11
Get Single Char from Console Immediately
Split String into a List, But Keeping the Split Pattern
What Is an Illegal Octal Digit
Tell Ruby Program to Wait Some Amount of Time
Ruby Regexp Group Matching, Assign Variables on 1 Line
Get Current Ruby Process Memory Usage
How to Calculate the Distance Between Two Gps Coordinates Without Using Google Maps API
Simple Encryption in Ruby Without External Gems
Error: SASS Installation for Windows
How to Use Hash Keys as Methods on a Class
Is There an Expect Equivalent Gem for Ruby
How to Dynamically Alter Inheritance in Ruby
Google Maps, Ruby on Rails, Zoom Level with One Marker
How to Map and Remove Nil Values in Ruby