File I/O
Reading from a File
# Example 1: Reading the entire file at once
file_path = 'example.txt'
# Open the file in read mode
File.open(file_path, 'r') do |file|
content = file.read
puts "File Content:\n#{content}"
end
# Example 2: Reading line by line
File.open(file_path, 'r') do |file|
file.each_line do |line|
puts "Line: #{line}"
end
end
Writing to a File
# Example 3: Writing to a file (replaces existing content)
file_path = 'example.txt'
# Open the file in write mode
File.open(file_path, 'w') do |file|
file.puts "Hello, World!"
file.puts "This is a new line."
end
# Example 4: Appending to a file
File.open(file_path, 'a') do |file|
file.puts "Appending more content."
end
Checking if a File Exists
file_path = 'example.txt'
if File.exist?(file_path)
puts "#{file_path} exists!"
else
puts "#{file_path} does not exist."
end
Handling File Exceptions
file_path = 'nonexistent_file.txt'
begin
File.open(file_path, 'r') do |file|
content = file.read
puts "File Content:\n#{content}"
end
rescue Errno::ENOENT
puts "File not found: #{file_path}"
rescue StandardError => e
puts "An error occurred: #{e.message}"
end
Loading...
> code result goes here