[Tutor] inserting path to open a file from a variable

richard kappler richkappler at gmail.com
Thu May 28 19:39:02 CEST 2015


This is a continuation of the read data script I asked for help on
yesterday, which works very well thanks to all the help from the list.

My script opens and reads in new lines from an in service log file,
extracts specific data, writes it to another file for analysis. All of that
works fine, tested out great.

Now I've been tasked to change the script so that the script doesn't need
to be in the same directory as the log file, which makes perfect sense.
Furthermore, the path can't be hard coded into the script, but rather
should read the installer should be able to edit a text file to specify the
paths to the read file (log from which we're extracting data) and the write
file (file to which we're send the extracted data). I thought this would be
a trivial exercise, but I'm stuck.

This is python 2.6.6 running on a Linux machine.

I've created a config file which the user would edit named fileMonitor.conf:

# line two is the absolute path to the log you are parsing data from
# keep 'rdfile:' as is, path starts after it, no spaces
rdfile:Documents/MyScripts/fileMonitor/log.txt
# line 4 is the absolute path to the log you are appending the parsed data
too
# keep 'wrtfile:' as is, path starts after it, no spaces
wrtfile:Documents/MyScripts/fileMonitor/newlog.txt

and I have written up a script that reads the paths and strips off the
unusable bit named readConfig.py:

# read the config file to get file locations for a script
conf = open('fileMonitor.conf', 'r')
read_it = conf.read()

for line in read_it.splitlines():
    if line.startswith('rdfile:'):
        rd = line
    elif line.startswith('wrtfile:'):
        wrt = line

rd1 = rd.replace('rdfile:',"",1)
wrt1 = wrt.replace('wrtfile:',"",1)

This worked fine, if I print rd1 and wrt1 I get just the paths that are
entered into the conf file.

Now I need to add that into my fileMonitor.py (parses log for data
extraction) so it goes to the two files.

At the moment, I am, for example, opening the file to be read from with a
simple

file = open('log.txt', 'r')

but I need to replace 'log.txt' with rd1 (path and file name to log.txt).

And I'm stumped. rd1 and wrt1 exist, I can print them, and I get what I
expect (path/filename) for example print rd1 gives
me Documents/MyScripts/fileMonitor/log.txt

But how in the heck do I get that into the open() statement?

What I've tried (none worked):
file = open(rd1, 'r')
file = open('rd1', 'r')

and I ran out of ideas.

Help?

regards, Richard




-- 

Windows assumes you are an idiot…Linux demands proof.


More information about the Tutor mailing list