Ruby/File Directory/Open a File
Материал из Wiki.crossplatform.ru
Версия от 17:10, 26 мая 2010; (Обсуждение)
Latin-1 transcoded to UTF-8 in File.open
in = File.open("data.txt", "r:iso8859-1:utf-8"); # Latin-1 transcoded to UTF-8
Open a file for reading binary data
File.open("data", "r:binary") # Open a file for reading binary data
Open a file in a mode where it can be read from and written to at the same time
f = File.open("text.txt", "r+") puts f.gets f.puts "This is a test" puts f.gets f.close
open file block
# Put some stuff into a file. open("sample_file", "w") do |f| f.write("This is line one.\nThis is line two.") end open("sample_file").each { |x| p x } # "This is line one.\n" # "This is line two."
opens up your text.txt file:
File.open("text.txt").each { |line| puts line }
Read UTF-8 text
in = File.open("data.txt", "r:utf-8"); # Read UTF-8 text
The Different Modes of Opening a File
MODES WHAT IT IMPLIES r Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode. r+ Read-write mode. The file pointer will be at the beginning of the file. w Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. w+ Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. a Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. a+ Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
The second parameter "r" defines that you"re opening the file for reading.
File.new("text.txt", "r").each { |line| puts line }
Write UTF-8 text
out = File.open("log", "a:utf-8"); # Write UTF-8 text