Ruby Common File Manipulation code example _ruby topic

Source: Internet
Author: User
#建立一个222. rb file and enter the character file = File.Open ("222.rb", "w+") file.puts "123\NWADWA\N12124124\NDWDW" File.close #输出222. RB Content Fil
E.open ("222.rb", "r+") do |file|
While line = File.gets puts line end #直接用IO操作文件 Io.foreach ("222.rb") do |line| Puts lines if line =~/abc/#输出匹配到了 ' abc ' of the row where the ' puts ' if line!~/qwe/#输出没有匹配到 ' Qwe ' is the row end #输出文件的绝对路径 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 "is exist ? --> "puts File.exist?" ("Asd.txt") #判断文件是否存在 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 \ \ 12345 ") Ios.seek (5) #把偏移指针移到5 (e-letter location) ios.puts (" Xyz3 ") #从5开始覆写原有数据 puts Ios.tell #tell--returns the current offset (in bytes) 
of iOS. Puts Ios.string puts iOS.String.dump #忽略 \ n Escaped #another example require ' stringio ' iOS = stringio.new ("Abcdef\nq9ert \ 12345") Ios.seek (3) ios.un Getc (? w) #replace the char at index 3 puts "PTR = #{ios.tell}" S1 = ios.gets #filte the "\ n" s2 = Ios.gets puts S1-puts s 2 #Ruby打开文件并写入数据操作 txt = file.open ("File path", "w+") txt.puts ' contents of file to be written ' txt.close #从文件里读取数据 num = file.readlines ("File path") [0]. Chomp #打开文件的方法 System ("Notepad file path")

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.