Reading a DOS text file and writing out Mac
Skip Montanaro
skip at pobox.com
Fri Jul 11 14:05:05 EDT 2003
Jen> Is there a way to set the EOL character that Python recognizes?
Not really.
Jen> For example, I'd like to set it to cr/lf (okay, that's eol
Jen> characters) when reading a file (DOS text) and set it to just cr
Jen> when writing out (Mac). Is there a way to do this?
Sure. Open the input file in Universal newline mode (add "U" to the open
flags) then write it in binary mode, appending the '\r' character yourself.
Universal newline mode is new in 2.3 however. You can always open the input
file in binary mode and explicitly strip any trailing \r\n pairs.
inf = open("somedosfile", "rb")
outf = open("somemacfile", "wb")
for line in inf.read().split("\r\n"):
outf.write(line+"\r")
inf.close()
outf.close()
or, if you're running 2.3:
inf = open("somedosfile", "rU")
outf = open("somemacfile", "wb")
for line in inf:
if line.endswith("\n"):
line = line[:-1]
outf.write(line+"\r")
inf.close()
outf.close()
Something like that should start you in the right direction.
Skip
More information about the Python-list
mailing list