0

I have the following file and I would like to replace #sys.path.insert(0, os.path.abspath('.')) with sys.path.extend(['path1', 'path2'])

import sys
import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

However, the following code does not change the line.

with open(os.path.join(conf_py_path, "conf.py"), 'r+') as cnfpy:
    for line in cnfpy:
        line.replace("#sys.path.insert(0, os.path.abspath('.')))",
                    "sys.path.extend(%s)\n" %src_paths)
        cnfpy.write(line)

How is it possible to replace the line?

user977828
  • 7,259
  • 16
  • 66
  • 117
  • 3
    http://stackoverflow.com/questions/9189172/python-string-replace –  Sep 20 '14 at 08:17
  • the problem can be demonstrated without opening a file. please strive to create a minimal example. – Karoly Horvath Sep 20 '14 at 08:19
  • We have two problems here: 1. Not saving the result of `line.replace()`, 2. Not reading and writing a file opened in `r+` mode correctly. – PM 2Ring Sep 20 '14 at 13:39

1 Answers1

1

Try fileinput to change a string in-place within a file:

import fileinput
for line in fileinput.input(filename, inplace=True):
    print(line.replace(string_to_replace, new_string))
Edmond Burnett
  • 4,829
  • 3
  • 18
  • 17