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

Alan Gauld alan.gauld at btinternet.com
Thu May 28 19:56:46 CEST 2015


On 28/05/15 18:39, richard kappler wrote:

> 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

You should maybe look at the config parser module and
use a standard file format. You are likely to be adding
more entries into this file...

> 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():

You should consider using something like

with open('fileMonitor.conf', 'r') as conf:
    for file in conf:

Rather rthan reading/splitting the file in memory.

> 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.
>
> file = open('log.txt', 'r')
>
> but I need to replace 'log.txt' with rd1 (path and file name to log.txt).
>
> What I've tried (none worked):
> file = open(rd1, 'r')

This should have worked.

What happened when you tried it? "Did not work" is a tad vague!


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list