Results 1 to 5 of 5

Thread: Change text/code/numbers in a file using Python

  1. #1
    Join Date
    Feb 2013
    Location
    UK, West Yorkshire
    Beans
    62
    Distro
    Xubuntu 14.04 Trusty Tahr

    Question Change text/code/numbers in a file using Python

    Hi, I am using python 3.2.3 and also a beginner in python programming.

    I would like to know how to go about changing words (or a string of words/numbers) in a file to something else.
    I can do this in bash
    For example:
    Code:
    sed -i 's/text_in_file/new_text/g' 'path_to_file'
    I know that there is some way to do this but I don't want to use os.system as a substitute.

    Any ideas?

    Thanks in advance.

  2. #2
    Join Date
    Aug 2011
    Location
    47°9′S 126°43W
    Beans
    2,165
    Distro
    Kubuntu 14.04 Trusty Tahr

    Re: Change text/code/numbers in a file using Python

    • read the file line by line (see open() built-in, and then "for line in file")
    • for simple editing, use the replace() method on strings, for more complex things, see the "re" module for regexps.
    • write output to another file.
    • optional: when done and if everything went OK, erase the original file and rename output file to original file name

  3. #3
    Join Date
    Feb 2013
    Location
    UK, West Yorkshire
    Beans
    62
    Distro
    Xubuntu 14.04 Trusty Tahr

    Re: Change text/code/numbers in a file using Python

    Ok, thanks. I will try later today.

  4. #4
    Join Date
    Feb 2013
    Location
    UK, West Yorkshire
    Beans
    62
    Distro
    Xubuntu 14.04 Trusty Tahr

    Re: Change text/code/numbers in a file using Python

    Sorry, but can you please explain a little further please as I cannot find anything in the python documentation about replace().

  5. #5
    Join Date
    Dec 2007
    Location
    Behind you!!
    Beans
    977
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Change text/code/numbers in a file using Python

    Quote Originally Posted by sudo san View Post
    Sorry, but can you please explain a little further please as I cannot find anything in the python documentation about replace().
    It's a string method
    http://docs.python.org/2/library/std...string-methods

    Code:
    line = "This is foo"
    line.replace("foo", "bar")
    computer-howto
    Linux is not windows
    Fluxbox & Flux menu how to
    Programming is an art. Learn it, Live it, Love it!


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •