Created
October 23, 2021 19:13
-
-
Save almokhtarbr/850f1bb099531faf80a9058978e29741 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Opening/Creating CSV File | |
First up, require the CSV library in your file. You don't need to install any gem for it, it comes bundled with your installation of ruby. | |
require "csv" | |
Then, to create a new CSV file you're going to; | |
csv = CSV.open("people.csv", "a+") | |
This will "open" a CSV file called "people.csv" in read-write mode where new writes will be added to the back of the file (append). If the file doesn't exist yet, it'll create it. Here's an overview of the different modes; | |
Modes Description | |
r Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode. | |
r+ Read-write mode. The file pointer will be at the beginning of the file. | |
w Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. | |
w+ Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. | |
a Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. | |
a+ Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. | |
Adding Data To CSV | |
# Adding new data | |
headers = ["name","height", "age","gender"] | |
CSV.open('file.csv', 'a+') do |row| | |
row << headers | |
end | |
Reading Data From CSV | |
# Reading data from CSV | |
file = CSV.read('exercises.csv', headers: true, header_converters: :symbol, converters: :all) | |
file.each_with_index do |row, i| | |
name = row[:name] | |
equipment = row[:equipment] | |
end | |
# OR | |
file = CSV.read('exercises.csv', headers: true, header_converters: :symbol, converters: :all) | |
file.map {|row| row.to_hash} | |
=> [{:name=>"Landmine 180's", | |
:equipment=>"Barbell", | |
:focus=>"Abdominals", | |
... }] | |
Options | |
headers: true # Removes headers from read | |
header_converters: :symbol # Allows each header to be accessed by their respective symbol | |
converters: :all # Converts each datatype to the correct ruby datatype ex: string representations of integers get converted into integer | |
Resources | |
Official Documentation: http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html | |
Fancy atom library for CSV edits: https://atom.io/packages/tablr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment