From: Peter Bailey Date: 2006-05-10T03:58:15+09:00 Subject: Re: Problem with 2nd File.Read in small script. Justin Collins wrote: > Peter Bailey wrote: >> require 'FileUtils' >> #If the page count is odd, then, add a blank to make it an even >> blankpages.push($1) >> File.open(infofile + ".pageinfo", "w") do |writetext| >> writetext << "Number of blankpages in this PDF: >> #{blankpages.length}\n" << >> "Blank Pages in This PDF: #{blankpages.join(' ')}\n" >> end >> end >> end >> end >> >> > > I think part of the issue here is that you open the file for writing, > then do a read on the same file. Looking at IO.read: > > Opens the file, optionally seeks to the given offset, then returns > /length/ bytes (defaulting to the rest of the file). read ensures the > file is closed before returning. > > But you have already opened the file. So, your structure above looks > something like: > > > File.open(psfile) { #opens psfile > > File.read(psfile) { #opens psfile > > } #closes psfile > > File.read(psfile) { #opens psfile > > } #closes psfile > > } #closes psfile > > > I'm not sure if that is the problem or not. > > -Justin Thanks, Justin. Your comments made me dive deeper, and, it works! Obviously, there shouldn't be any reason why I couldn't read a file twice, or as many times as I needed. But, I did make it neater here, closing one read before starting another. . . . require 'FileUtils' Dir.chdir("c:/scripts/ruby/temp") psfiles = Dir.glob('*.ps') blankpages = [] totalpages = 0 psfiles.each do |psfile| infofile = File.basename(psfile, '.ps') #Scan for the number of pages in the original PDF. File.read(psfile).scan(/\%\%Pages: (\d{1,5})\n/) do File.open(psfile, "a") do |writepage| totalpages = $1 #totalpages.push($1) #If the page count is odd, then, add a blank to make it an even page count. if (totalpages.to_i % 2) !=0 then writepage << "\%\%Blank page from Asura\nshowpage\n" totalpages = totalpages.to_i + 1.to_i end end end File.read(psfile).scan(/\%\%Page: [(\d)()]+ (\d{1,5})\n\%\%PageBoundingBox: \d{1,5} \d{1,5} \d{1,5} \d{1,5}\n\%\%PageOrientation:/) do blankpages = $1 end File.open(infofile + ".pageinfo", "w") do |writetext| writetext << "Total number of pages in this PDF: #{totalpages}\n" <<\ "Number of blank pages in this PDF: \ #{blankpages.length}\n" << "Blank Pages\ in This PDF: #{blankpages.join(' ')}\n" end end -- Posted via http://www.ruby-forum.com/.