Jsg91
Jsg91

Reputation: 465

Opening a subdirectory using a variable

Hi I currently have some code that extracts some info from various log files, xyz.log, there is also a subdirectory (xyz) that contains another file I want to extract some info from as well. I'm having trouble opening the subdirectory, My current code is like this:

for file in log_files:
if file == "1.log":
    linenum = 5
else:
    linenum = 4
with open(file, 'r') as f:
    for i, line in enumerate(f):
        if i == linenum:
            try:
                e = float(line.strip().split()[10])
                xyz = file[:-4]
                #here's where I would like to get the additional data
                    for i, line in enumerate(g):
                        if i == 34:
                            d = float(line.strip().split()[3])
                data.append( (xyz, e, d ))

I've tried using a with open with the path set to %xyz/fort.12 but that threw a syntax error I'm guessing the os module is my friend here but I'm pretty naff at using it. Does anyone have any ideas?

Upvotes: 1

Views: 60

Answers (1)

Blair
Blair

Reputation: 6693

You want os.path.join. It accepts any number of parameters and puts them together using the correct path seperator for whatever operating system that you are on.

for file in log_files:
if file == "1.log":
    linenum = 5
else:
    linenum = 4
with open(file, 'r') as f:
    for i, line in enumerate(f):
        if i == linenum:
            try:
                e = float(line.strip().split()[10])
                xyz = file[:-4]
                with open(os.path.join(xyz,'fort.12')) as g:
                    for i, line in enumerate(g):
                        if i == 34:
                            d = float(line.strip().split()[3])
                data.append( (xyz, e, d ))

Upvotes: 1

Related Questions