print dos format file into unix format

Magnus Lycka lycka at carmen.se
Fri Oct 27 15:56:13 CEST 2006


Tim Roberts wrote:
> "PengYu.UT at gmail.com" <PengYu.UT at gmail.com> wrote:
>> Suppose I have a dos format text file. The following python code will
>> print ^M at the end. I'm wondering how to print it in unix format.
>>
>> fh = open(options.filename)
>> for line in fh.readlines()
>>  print line,
> 
> Are you running this on Unix or on DOS?
> 
> On Unix, you can do:
> 
> for line in open(options.filename).readlines():
>     print line.rstrip()
> 
> Perhaps quicker is:
> 
> sys.stdout.write( open(options.filename).read().replace('\r\n','\n') )

There are more differences between text files than that.
I don't know any unix systems that uses CP 437 etc. I'd
convert the text to unicode through .decode('cp437') etc,
and then print that. If things aren't set up so than
unicode object print correctly, use
.decode('cp437').encode('utf8') etc to get it to an
appropriate encoding.



More information about the Python-list mailing list