|
# Create a 222. rb file and input characters
File = File. open ("222.rb"," w + ")
File. puts "123 \ nwadwa \ n12124124 \ ndwdw"
File. close
# Output 222. rb content
File. open ("222.rb"," r + ") do | file |
While line = file. gets
Puts line
End
End
# Directly using IO to operate files
IO. foreach ("222.rb") do | line |
Puts line if line = ~ /Abc/# The output matches the row of 'abc '.
Puts line if line !~ /Qwe/# The output does not match the row where 'qw' is located.
End
# Absolute path of the output file
Puts File. expand_path ("222.rb ")
# Count chars from a file
File = File. new ("222.rb ")
W_count = 0
File. each_byte do | byte |
W_count + = 1 if byte =? 1
End
Puts "# {w_count }"
# Create new file and write some words there
Print "The file now is exist? -->"
Puts File. exist? ("Asd.txt") # determine whether a file exists
File = File. new ("asd.txt", "w ")
Print "The file now is exist? -->"
Puts File. exist? ("Asd.txt ")
File. write ("hehe \ nhahah ")
# Io. stream operation
Require 'stringio'
Ios = StringIO. new ("abcdef \ n ABC \ n 12345 ")
Ios. seek (5) # Move the offset pointer to 5 (where the e letter is located)
Ios. puts ("xyz3") # overwrite the original data from 5
Puts ios. tell # tell -- Returns the current offset (in bytes) of ios.
Puts ios. string
Puts ios. string. dump # ignore the escape of \ n
# Another example
Require 'stringio'
Ios = StringIO. new ("abcdef \ nq9ert \ n 12345 ")
Ios. seek (3)
Ios. ungetc (? W) # replace the char at index 3
Puts "Ptr =#{ ios. tell }"
S1 = ios. gets # filte the "\ n"
S2 = ios. gets
Puts s1
Puts s2
# Ruby open a file and write data
Txt = File. open ("File path", "w + ")
Txt. puts 'content of the file to be written'
Txt. close
# Reading data from a file
Num = File. readlines ("File path") [0]. chomp
# How to open a file
System ("notepad file path ")
|