Convert UNIX formated text files to DOS formated?
google at mrabarnett.plus.com
Wed May 13 00:03:46 CEST 2009
> On May 12, 2:53 pm, MRAB <goo... at mrabarnett.plus.com> wrote:
>> walterbyrd wrote:
>>> I have about 150 unix formated text files that I would like to convert
>>> to dos formated.
>>> I am guessing that I loop though each file in the directory, read each
>>> line and conver the last character, then save to a file with the same
>>> name in another directory.
>>> I am not really sure what I convert the last charactor to.
>> The quickest and OS-agnostic way would be:
>> text = open(path, "U").read()
>> text = text.replace("\n", "\r\n")
>> open(path, "wb").write(text)
>> That way it doesn't matter if the text file is already dos formatted.
> Thanks, I am not familiar with the "U" here is how I did it:
> import os
> for file in os.listdir('.'):
> infile = open(file,'r')
> outfile = open( 'new_' + file, 'w')
> for line in infile:
> line = line.rstrip() + '\r\n'
> More code, probably slower, but it worked.
That will also strip any whitespace off the end of the lines.
FYI, if you run it on Windows then the resulting lines will end with
"\r\n\n" because the output file is opened in text mode, which will
write any "\n" as "\r\n".
More information about the Python-list