Ruby common file operation code examples

Time:2022-4-29
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#Build a 222 RB file and enter characters
file = File.open("222.rb","w+")
file.puts "123\nwadwa\n12124124\ndwdw"
file.close
 
 
#Output 222 Content of RB
File.open("222.rb","r+") do |file|
while line = file.gets
puts line
end
end
 
 
#Operate files directly with IO
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 line of 'qwe'
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 the 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 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 file and write data operation
txt = File.open("File path","w+")
txt.puts 'file contents to write'
txt.close
#Read data from file
num = File.readlines("File path")[0].chomp
#How to open a file
system("Notepad file path")