File Handling in Ruby
Ruby provides simple and intuitive methods for file handling using the File
class.
Reading a File
Use the File.read
method to read the contents of a file.
content = File.read("example.txt")
puts content
Writing to a File
Use the File.write
method to write data to a file.
File.write("example.txt", "Hello, Ruby!")
Appending to a File
Use the File.open
method with the append mode to add data to a file.
File.open("example.txt", "a") do |file|
file.puts "Appending this line!"
end
File Modes
Ruby supports various file modes for different operations:
"r"
: Read-only (default)."w"
: Write-only. Creates a new file or truncates an existing file."a"
: Append-only. Creates a new file or appends to an existing file."r+"
: Read and write."w+"
: Read and write. Creates a new file or truncates an existing file."a+"
: Read and append. Creates a new file or appends to an existing file.
Reading Line by Line
Use File.foreach
to read a file line by line.
File.foreach("example.txt") do |line|
puts line
end
File Metadata
Ruby provides methods to access file metadata, such as size, modification time, and file type.
puts "File size: #{File.size("example.txt")} bytes"
puts "Last modified: #{File.mtime("example.txt")}"
puts "Is a directory? #{File.directory?("example.txt")}"
Error Handling
Always handle errors when working with files to avoid crashes.
begin
File.open("nonexistent_file.txt") do |file|
puts file.read
end
rescue Errno::ENOENT => e
puts "File not found: #{e.message}"
end
Best Practices
- Use Blocks: Always use blocks with
File.open
to ensure files are properly closed. - Check File Existence: Use
File.exist?
to check if a file exists before opening it. - Handle Errors: Use
begin-rescue
blocks to handle file-related errors gracefully. - Use Appropriate Modes: Choose the correct file mode for your operation.