Created
November 24, 2013 16:01
-
-
Save katsuhide/7628703 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
## ファイル名の取得 | |
puts File.basename(__FILE__) | |
## 拡張子を除くファイル名 | |
puts File.basename(__FILE__, File.extname(__FILE__)) | |
## 拡張子 | |
puts File.extname(__FILE__) | |
## テキストファイルを読み込む | |
f = open("file.txt") | |
f.each{|line| | |
puts line | |
} | |
## 読み込んだテキストファイルを配列に変換 | |
f = open("file.txt") | |
array = f.readlines() | |
## ファイルに出力 a:追記モード, w:新規モード | |
File.open('resutl.txt', 'a'){|file| | |
file.write(j) | |
file.write("\n") | |
} | |
## jsonをファイルに出力する | |
open("tweet.json", "w") do |io| | |
JSON.dump(j, io) | |
end | |
## csvファイルを読み込む | |
### 配列で読み込む | |
array = CSV.read("hoge.csv") | |
### tableで読み込む | |
table = CSV.table("hoge.csv") | |
### ヘッダーを取得 | |
table.headers | |
### 列で取得 | |
table[:name] | |
### 行で数得 | |
table[1] | |
## csvファイルを書き込む | |
CSV.open("hoge.csv", "w") do |csv| | |
csv << ["hoge", 1111] | |
csv << ["fuga", 2222] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment