read/write file problem

j vickroy jvickroy at sec.noaa.gov
Mon Apr 17 15:36:53 CEST 2000


Hello all,

I am attempting to read and, subsequently, write a jpeg file.
The following interactive session illustrates the problem I am having
(i.e., if the source file is read byte-by-byte into memory and
subsequently
rewritten using the file.write() method, only the initial portion of the

file appears to be written).
How should I be doing this in Python 1.5.2.

Thanks for your time.


>>> import os.path
>>> file_name = 'd:/p1010001.jpg'
>>> source_byte_cnt = os.path.getsize (file_name)
>>> print source_byte_cnt
381965
>>> buf = []
>>> file = open (file_name, 'r')
>>> for i in xrange (0,source_byte_cnt):
...  buf .append (file .read(1))
...
>>> file .close()
>>> print len (buf) == source_byte_cnt
1
>>> file_name = 'd:/test.jpg'
>>> file = open (file_name, 'w')
>>> for i in xrange (0,source_byte_cnt):
...  file .write (buf[i])
...
>>> file .close()
>>> target_byte_cnt = os.path.getsize (file_name)
>>> print target_byte_cnt
70
>>> file = open (file_name, 'w')
>>> for i in xrange (0,source_byte_cnt):
...  file .write (str(buf[i]))
...
>>> file .close()
>>> target_byte_cnt = os.path.getsize (file_name)
>>> print target_byte_cnt
70
>>>





More information about the Python-list mailing list