Removing newlines from string on windows (without replacing)
rhodri at wildebst.demon.co.uk
Sat Jul 25 22:08:54 CEST 2009
On Sat, 25 Jul 2009 20:27:37 +0100, Tom <tom.sully at gmx.com> wrote:
> This is my first post to this mailing list, so hi :)
> I have an annoying problem. While I mainly use Linux when I distribute
> this program to friends and on the internet, it'll get used on Windows.
> So, I tested my python program on my Windows Vista dual boot, running
> the same version of python (2.6) as my Linux, and got an error at the
> following code.
> s = sauce.replace("\n", "")
What error? (I don't let Vista in the house.)
> Sauce is a string, read from a file, that I need to remove newlines
> from. This code works fine in Linux, but not in Windows. rstrip("\n")
> won't work for me, so anybody know how to get this working on Windows?
Why won't rstrip("\n") work? Is rstrip() OK instead, or does trailing
whitespace matter to you?
To provide a partial answer, your problem probably lies in the different
ways Windows and Linux treat ends of lines. Under Linux, "\n" is the
line terminator. Under Windows, it's "\r\n". If you opened your file
in "byte mode" with open("myfile.txt", "rb"), you will be given all the
bytes in the file, including those extra "\r" characters on Windows. If
you open your file in text mode with open("myfile.txt, "r") instead, the
line endings are converted to "\n" on both Windows and Linux.
If my crystal ball has proved faulty, giving us more details will help
get a more sensible answer.
Rhodri James *-* Wildebeest Herder to the Masses
More information about the Python-list