วันนี้เรียนรู้อ่านและเขียนไฟล์ใน Ruby เพื่อ extract contents, สร้างไฟล์ใหม่ และหาข้อมูลที่ต้องการ!

นี่คือสิ่งที่เราจะครอบคลุม:
สารบัญ
- 1 วิธีอ่านไฟล์ใน Ruby
- 2 วิธีเขียนไฟล์ใน Ruby
- 3 Ruby File Methods
- 4 Directory Operations
- 5 วิธีใช้ FileUtils Module
- 6 สรุป
- 6.1 Related
มาเริ่มกัน!
วิธีอ่านไฟล์ใน Ruby
อ่านไฟล์ใน Ruby แบบนี้:
- เปิดไฟล์ ด้วย
openmethod - อ่านไฟล์ ทั้งไฟล์, บรรทัดต่อบรรทัด, หรือจำนวน bytes เฉพาะ
- ปิดไฟล์ ด้วย
closemethod
รายละเอียดกระบวนการ:
用 File class เปิดไฟล์:
file = File.open("users.txt")
ได้ File object แต่ยังไม่ใช่ contents
现在: อ่าน contents 3 วิธี แรก อ่านทั้งไฟล์:
file_data = file.read # "user1\nuser2\nuser3\n"
ไฟล์หลายบรรทัด ใช้ split กับ file_data หรือ readlines + chomp ลบ newline characters
例子:
file_data = file.readlines.map(&:chomp) # ["user1", "user2", "user3"]
จบงานกับไฟล์ close เพื่อ釋放 memory และ system resources
file.close
替代方案 不用 开 关 文件: 用 File.read method:
file_data = File.read("user.txt").split # ["user1", "user2", "user3"]
Tip อ่านไฟล์อีกอย่าง: อยาก process ไฟล์ทีละบรรทัด ใช้ foreach method
例子:
File.foreach("users.txt") { |line| puts line }
แทน อ่านทั้งไฟล์เข้า memory process ทีละบรรทัด ใช้สำหรับไฟล์ใหญ่
วิธีเขียนไฟล์ใน Ruby
อยากเขียนไฟล์ด้วย Ruby:
- เปิดไฟล์ write mode ("w" flag)
- 用
writemethod 加 数据 到 文件 - 如果 没用 block version 记着
close
例子:
File.open("log.txt", "w") { |f| f.write "#{Time.now} - User logged in\n" }
重要: 这 会 重写 之前 文件 contents!
อยาก เพิ่ม content ใหม่ 进 文件 用 "a" (append) flag 代替 "w" (write) flag
Shortcut: 用 File.write:
File.write("log.txt", "data...")
用这 method append mode:
File.write("log.txt", "data...", mode: "a")
这是 最 简单 方式 写 文件 Ruby 一行 code 🙂
还有一件事... 写 array 进 文件 要 转 string 先
怎么做:
File.write("log.txt", [1,2,3].join("\n"), mode: "a")
过程 转 object 成 string 叫 serialization
Ruby File Methods
做 别的 事 跟 文件 除了 读 写 如 想 知道 文件 存在 不 或 列表 文件 current directory
将 用 methods 如:
- rename
- size
- exists?
- extname
- basename
- dirname
- directory?
- file?
例子 少少:
# 重命名 文件
File.rename("old-name.txt", "new-name.txt")
# 文件 大小 bytes
File.size("users.txt")
# 这 文件 已经 存在?
File.exists?("log.txt")
# 取 文件 extension, 即使 文件 不 存在 也 行
File.extname("users.txt") # => ".txt"
# 取 文件名 不要 directory part
File.basename("/tmp/ebook.pdf") # => "ebook.pdf"
# 取 path 这 文件 不要 文件名
File.dirname("/tmp/ebook.pdf") # => "/tmp"
# 这 真 是 文件 或 目录?
File.directory?("cats")
例子 最后 有 意思 如果 loop 通过 directory listing contents
def find_files_in_current_directory
entries = Dir.entries(".")
entries.reject { |entry| File.directory?(entry) }
end
也 能 取 stats 文件 如 大小, permissions, creation date:
File.stat("/tmp")
Directory Operations
用 Dir.glob 取 列表 所有 文件 match pattern
例子:
# 所有 文件 current directory
Dir.glob("*")
# 所有 文件 包含 "spec" 在 名字
Dir.glob("*spec*")
# 所有 ruby 文件
Dir.glob("*.rb")
一行 code recursively 列出 所有 文件 Ruby 从 current directory:
Dir.glob("**/**")
用 这 如果 只 要 搜 目录:
Dir.glob("**/**/")
用 Dir class 也 能 印 current working directory:
Dir.pwd
检查 目录 空:
Dir.empty?("/tmp") # false
检查 目录 存在:
Dir.exists?("/home/jesus") # true
创建 新 目录:
Dir.mkdir("/tmp/testing")
创建 temporary directory 用 mktmpdir:
Dir.mktmpdir do |dir| File.write(dir + "/log.txt", "test") end
怎么用 FileUtils Module
额外 file handling utilities 在 FileUtils module
如 比较 文件, touch 文件 (更新 last access 和 modification time), 或 copy 文件 和 目录 cp_r
像这样:
require 'fileutils'
FileUtils.compare_file("a.txt", "b.txt")
FileUtils.touch("/tmp/lock")
FileUtils.cp_r("data", "backup")
Btw "r" 在 cp_r 意思 "recursive"
总结
学会 管理 文件 和 文件夹 Ruby 用 built-in methods 如 File.read 和 File.write
谢谢 阅读!