# Size change after file writing

**URL:** <https://www.ruby-forum.com/t/size-change-after-file-writing/110775>\
**Category:** Ruby\
**Created:** [July 30, 2007, 8:50pm UTC](https://www.ruby-forum.com/t/size-change-after-file-writing/110775 "2007-07-30T20:50:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [July 30, 2007, 8:50pm UTC](https://www.ruby-forum.com/t/size-change-after-file-writing/110775/1 "2007-07-30T20:50:20Z")

</div>

Hi all,

I write a small script to read old files and write to new files. Either  
reading line by line or whole file at once then I ask Ruby to write to  
new files. The new file is much smaller than the old one. I also find  
that the new file losses many information. How to explain this?

Thanks,

Li

#################script-1 read file line by line and write to a new file  
path=‘C:\Allo12-Y2’  
file\_names=[]

Dir.open(path).each do|f|  
file\_names\<\<path+"\#{f}" unless f=~/^..\*$/  
end

file\_names.each do|f|  
new\_file=File.open("#{f}b",‘w’)  
File.open(f,‘r’) do|file|  
file.each\_line{|line|new\_file.print line }  
end  
end

###################sctript-2 read whole file and write to a new file

path=‘C:\Allo12-Y2’  
file\_names=[]

Dir.open(path).each do|f|  
file\_names\<\<path+"\#{f}" unless f=~/^..\*$/  
end

file\_names.each do|f|  
file=File.open(f,‘r’) #open file for read  
new\_file=File.open("#{f}b",‘w’)#open file for write  
new\_file.print file.read #write old file to new file  
end

### size in old file: AlloY2.001 is 609kb

```
size in new file: AlloY2.001b is 47bk
```

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [July 30, 2007, 9:44pm UTC](https://www.ruby-forum.com/t/size-change-after-file-writing/110775/2 "2007-07-30T21:44:41Z")

</div>

Hi,

At Tue, 31 Jul 2007 03:50:24 +0900,  
Li Chen wrote in [ruby-talk:262503]:

> I write a small script to read old files and write to new files. Either  
> reading line by line or whole file at once then I ask Ruby to write to  
> new files. The new file is much smaller than the old one. I also find  
> that the new file losses many information. How to explain this?

Use “rb” and “wb” mode for binary files, or better, use FileUtils.cp.

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [July 30, 2007, 9:59pm UTC](https://www.ruby-forum.com/t/size-change-after-file-writing/110775/3 "2007-07-30T21:59:47Z")

</div>

Nobuyoshi N. wrote:

> Use “rb” and “wb” mode for binary files, or better, use FileUtils.cp.

Thank you very much and they work well.

Li
