使用变量打开子目录

时间:2013-06-19 14:07:10

标签: python

您好我目前有一些代码从各种日志文件中提取一些信息,xyz.log,还有一个子目录(xyz),其中包含另一个我想从中提取一些信息的文件。我打开子目录时遇到问题,我目前的代码是这样的:

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

我尝试使用带有设置为%xyz / fort.12的路径的open,但是这引发了语法错误我猜测os模块是我的朋友,但我非常擅长使用它。有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

你想要os.path.join。它接受任意数量的参数,并使用正确的路径分隔符将它们放在一起,以适用于您所使用的任何操作系统。

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