python - 使用变量打开子目录

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

我尝试使用 with open 并将路径设置为 %xyz/fort.12 但这引发了语法错误我猜测 os 模块是我的 friend ,但我对使用它非常不熟悉。有人有什么想法吗?

最佳答案

你想要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 ))

关于python - 使用变量打开子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17193413/

相关文章:

python - python 正则表达式是否有不编译 r'(\s*)+' 的原因?

python - TypeError : Expected float32 passed to parameter 'y' of op 'Equal' , 得到了类型为 'auto' 的 'str'

python - For Loop with If 语句只返回第一个元素

python - Django 中的单例对象行为

Python:在 matplotlib.pyplot 上绘制子列表

Python - 带参数和逗号的 MySQL 查询

python - 找到 pandas 中另一列中每个数字条纹的最大值

python - Pyinstaller 中的多个隐藏导入

python - 使用 python 读取 .dat 文件

python - 提取每个子列表的第一项