File Object behavior

Steven Bethard steven.bethard at gmail.com
Tue Apr 3 14:11:48 EDT 2007


Michael Castleton wrote:
> When I open a csv or txt file with:
> 
> infile = open(sys.argv[1],'rb').readlines()
> or 
> infile = open(sys.argv[1],'rb').read()
> 
> and then look at the first few lines of the file there is a carriage return
> + 
> line feed at the end of each line - \r\n
> This is fine and somewhat expected.  My problem comes from then writing
> infile out to a new file with:
> 
> outfile = open(sys.argv[2],'w')
> outfile.writelines(infile)
> outfile.close()
> 
> at which point an additional carriage return is inserted to the end of each
> line - \r\r\n

Maybe because you're reading the file as binary ('rb') but writing it as 
  text ('w')::

     >>> open('temp.txt', 'w').write('hello\r\n')
     >>> open('temp.txt', 'rb').read()
     'hello\r\r\n'
     >>> open('temp.txt', 'wb').write('hello\r\n')
     >>> open('temp.txt', 'rb').read()
     'hello\r\n'
     >>> open('temp.txt', 'w').write('hello\r\n')
     >>> open('temp.txt', 'r').read()
     'hello\r\n'

Looks like if you match your writes and reads everything works out fine.

STeVe



More information about the Python-list mailing list