line break confusion
Fernando Perez
fperez528 at yahoo.com
Fri Feb 15 23:01:00 EST 2002
Michael Mell wrote:
> Using Python 2.2 running on any arbitrary OS (Linux, Win, Mac), I want
> to
> 1) read several files having an arbitrary mix of line break types
> (Linux, Win, Mac)
> 2) then standardize the breaks of each of the files to a single type
> and
> 3) then concatenate them all into a string for writing.
This is probably a useful start:
#-----------------------------------------------------------------------------
def native_line_ends(file,backup=1):
"""Convert (in-place) a file to line-ends native to the current OS.
If the optional backup argument is given as false, no backup of the
original file is left. """
backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
bak_file = file + backup_suffixes[os.name]
original = open(file).read()
shutil.copy2(file,bak_file)
try:
new = open(file,'w')
new.write(os.linesep.join(original.splitlines()))
new.write(os.linesep) # ALWAYS put an eol at the end of the file
new.close()
except:
os.rename(bak_file,file)
if not backup:
try:
os.remove(bak_file)
except:
pass
Modify it to suit your needs.
Cheers,
f.
More information about the Python-list
mailing list