user1488804
user1488804

Reputation: 860

How to 'add' text to a file using a python function

I have a configuration file called conf.py. When running a python program that uses it, I'd like it to 'see' additional text at the file, without actually modifying the file.

What I intend to do is to call a python function at the end of the file, so that when conf.py gets parsed by another program, it 'sees' the text that is stored in the string, returned by this function.

conf.py looks a little like this:

option1 = [...]
option2 = [...]

myFuncion()

where myFunction is something along the lines of:

def myFunction():
    f = open('MyFile.py', 'r')
    string = str(f.readlines())
    f.close()
    return string

When parsed, I'd like conf.py to look like

option1 = [...]
option2 = [...]

option3 = [...]
option4 = [...]

where these latter 2 options are contained within MyFile.py.

Any ideas?

Thanks

Upvotes: 0

Views: 567

Answers (1)

tdelaney
tdelaney

Reputation: 77337

You can do this by importing MyFile.py, the trick is making sure that python can find it. Suppose you have '/path/to/MyFile.py'. You can do something like

conf.py

import sys
sys.path.insert(0, '/path/to/')

option1 = 'abc'
option2 = 'def'

from MyFile import option3, option4

Upvotes: 1

Related Questions