&tag(Ruby/ファイル);
#オーソドックスな読み込み
File.open("/tmp/test.txt") do |f|
puts f.read
end
str = File.read("/tmp/test.txt")
puts str
File.readlines(path)
File.open("/tmp/test.txt", "w") do |f|
f.puts("This is test1")
end
File.write("/tmp/text.txt", "This is test") def write_bom(fp)
data = " "
data.setbyte(0, 0xEF)
data.setbyte(1, 0xBB)
data.setbyte(2, 0xBF)
fp.write(data)
end
Dir.glob("/tmp/*.jpg")
=> ["d:/temp/empty.jpg", "d:/temp/ipad.jpg"] Dir.glob("*.{htm,html}")Dir.glob("/tmp/**/*.jpg")ワイルドカードを指定できる(正規表現ではない)。
p Dir::entries("d:/temp")
=> [".", "..", "empty.jpg", "ipad.jpg"]
戻り値はファイル名のみ。
dir = "d:/temp/"
p Dir.entries(dir).collect{|f| dir + f}
=> ["d:/temp/.", "d:/temp/..", "d:/temp/empty.jpg", "d:/temp/ipad.jpg"]
dir = "d:/temp/"
p Dir.entries(dir).grep(/\.jpg$/) {|f| dir + f}
=> ["d:/temp/empty.jpg", "d:/temp/ipad.jpg"]
grepに渡す正規表現を工夫すればよい。
dir = "d:/temp/"
p Dir.entries(dir).grep(/\.(jpg|png)$/) {|f| dir + f}
=> ["d:/temp/abc.png", "d:/temp/empty.jpg", "d:/temp/ipad.jpg"]
FileUtils.rm("d:/temp/foo.txt")
FileUtils.rm(Dir.glob("d:/temp/*.jpg"))
require File.expand_path('../../a.rb', __FILE__)require 'pathname'
path = Pathname.new("/tmp")
path += 'sample.txt' #結合できる。戻り値はPathnameオブジェクト
p path # => #<Pathname:/tmp/sample.txt>
.zipファイルを圧縮解凍するためのライブラリ。
Zip::File.open('data/demo.zip') do |zipfile|
zipfile.each do |entry|
puts "extracting #{entry.name}"
entry.extract('tmp/' + entry.name)
end
end
f = File.open("log.txt", "w")
f.print("abc\r\n")
f.close
abc^M