Ruby/File Directory/Text file
Материал из Wiki.crossplatform.ru
Содержание |
Output each line in a file and close it
file = File.open( "myFile.txt" ) file.each { |line| print "#{file.lineno}. ", line } file.close
Read a text file readlines
# 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") { |f| f.readlines } # => ["This is line one.\n", "This is line two."]
Read a text file with File.read
# Put some stuff into a file. open("sample_file", "w") do |f| f.write("This is line one.\nThis is line two.") end File.read("sample_file") # => "This is line one.\nThis is line two."
Read line from a text file
file = File.new( "yourFile.txt" ) file.readline # => "Let me not to the marriage of true minds\n" file.readline # => "Admit impediments. Love is not love\n" file.readline # => "Which alters when it alteration finds,\n" file.close
Replace string in a file
def stringReplace(searchString, replaceString, fileName) aFile = File.open(fileName, "r") aString = aFile.read aFile.close aString.gsub!(searchString, replaceString) File.open(fileName, "w") { |file| file << aString } end stringReplace(*ARGV)
Use code block to insert string to a file
open("s.html", "wb") do |f| f << "<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">" f << "\xe2\x98\xBA" end
Use each method to loop through a text file
#!/usr/bin/env ruby file = File.open( "myFile.txt" ) file.each { |line| print "#{file.lineno}. ", line } file.close