---
title: "ruby 1.9 简单的文件操作"
author: "夜鸣猪"
date: "2011-11-21T00:23:36Z"
tags: []
categories: ["编程语言"]
slug: "ruby-1-9"
draft: false
lastmod: "2012-02-15T07:15:43Z"
id: 1269795
url: "https://hlee.iteye.com/blog/1269795"
---

```ruby

#读文件
f = File.open("myfile.txt", "r")
f.each_line do|line|
puts "I read this line: #{line}"
end


```



```ruby

File.foreach("myfile.txt") do|line|
puts "I read this line: #{line}"
end

```



```ruby
f = File.open("myfile.txt", "r")
line = f.gets
puts "The line I read is: #{line}"
```



```ruby

#写操作
File.open('filename','w') do |f|
  f.puts lines
end

```



```ruby

#得到当前目录所有文件名
    files = Dir.glob('*.rd')

```



```ruby

#删除特定目录所有文件名
Dir.glob('*.rd').each{|f| File.delete f}

```



```ruby

open('myfile.out', 'a') { |f|
  f << "Four score\n"
  f << "and seven\n"
  f << "years ago\n"
}

```



官网File API介绍
<http://www.ruby-doc.org/core-1.9.3/File.html>