File Object behavior

7stud bbxx789_05ss at yahoo.com
Tue Apr 3 20:26:24 CEST 2007


On Apr 3, 12:02 pm, Michael Castleton <fatuhe... at yahoo.com> 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
> The same behavior occurs with outfile.write(infile) also. I am doing no
> processing
> between reading the input and writing to the output.
 The file.writelines() documentation says that it
> doesn't add line separators. Is adding a carriage return something
> different?
> At this point I have to filter out the additional carriage return which
> seems like
> extra and unnecessary effort.
> I am using Python 2.4 on Windows XP sp2.
> Can anybody help me understand this situation?
>
> Thanks
> --
> View this message in context:http://www.nabble.com/File-Object-behavior-tf3520070.html#a9821538
> Sent from the Python - python-list mailing list archive at Nabble.com.

> The file.writelines() documentation says that it
> doesn't add line separators. Is adding a carriage return something
> different?

No.

> Is this expected behavior?

According to Python in a Nutshell(p. 217) it is.  On windows, in text
mode, when you write a \n to a file, the \n is converted to the system
specific newline (which is specified in os.linesep).  For windows, a
newline is \r\n.  Conversely, on windows, in text mode, when you read
a \r\n newline from a file, it is converted to a \n.




More information about the Python-list mailing list