4 回答

TA貢獻1804條經驗 獲得超3個贊
File.open("my/file/path", "r") do |f|
f.each_line do |line|
puts line
end
end
# File is closed automatically at end of block
也可以在上述之后顯式關閉文件(傳遞一個塊open為您關閉文件):
f = File.open("my/file/path", "r")
f.each_line do |line|
puts line
end
f.close

TA貢獻1802條經驗 獲得超5個贊
您可以一次讀取所有文件:
content = File.readlines 'file.txt'
content.each_with_index{|line, i| puts "#{i+1}: #{line}"}
當文件很大或可能很大時,通常最好逐行處理它:
File.foreach( 'file.txt' ) do |line|
puts line
end
有時,您可能想要訪問文件句柄,或者自己控制讀?。?/p>
File.open( 'file.txt' ) do |f|
loop do
break if not line = f.gets
puts "#{f.lineno}: #{line}"
end
end
如果是二進制文件,則可以指定nil-separator和塊大小,如下所示:
File.open('file.bin', 'rb') do |f|
loop do
break if not buf = f.gets(nil, 80)
puts buf.unpack('H*')
end
end
最后,您可以無障礙地執行此操作,例如,當同時處理多個文件時。在這種情況下,必須顯式關閉文件(根據@antinome的注釋進行改進):
begin
f = File.open 'file.txt'
while line = f.gets
puts line
end
ensure
f.close
end
參考:File API和IO API。
- 4 回答
- 0 關注
- 952 瀏覽
添加回答
舉報