[Tutor] Removing characters

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 14 Oct 2001 18:05:24 -0700 (PDT)


On Sun, 14 Oct 2001, Timothy M. Brauch wrote:

> I know there must a simple way to open a file and remove all the end
> of line characters and/or carriage returns.  However, I can't seem to
> get it to work right.  Any help?

What sort of problems are you running into?  If you can show us, we might
be able to spot the bug that's causing problems.


I do have a script below that will do the job, below the spoiler space.  
Hope this helps!

*** Spoiler space below ***



















"""trim_file.py --- Removes all end of line characters and carriage
returns in a file, and moves the original into a backup file, just in case
things go horribly wrong.

Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
"""

import sys, os, time


def trimFile(filename):
    """Trims the newlines and carriage returns out of a file."""
    contents = readContents(filename)
    contents = replaceWeirdCharacters(contents)
    writeContents(filename, contents)


def readContents(filename):
    """Returns the contents of a file."""
    return open(filename).read()


def writeContents(filename, contents):
    """Writes out the contents to filename, and backs things up just
    in case bad things happen."""
    os.rename(filename,
              filename + "-backup." + time.strftime("%m-%d-%Y"))
    out = open(filename, "w")
    out.write(contents)
    out.flush()
    out.close()


def replaceWeirdCharacters(contents):
    """Removes newlines and carriage returns from a string, and returns
    this cleaned-up string to the user.

    Note: this uses Python 2.1 string methods: it might be better
    to use the string.replace() function instead for compatibility."""
    return contents.replace("\n", "").replace("\r", "")


if __name__ == '__main__':
    for filename in sys.argv[1:]:
        trimFile(filename)