嗨,我目前有一些代码可以从各种日志文件 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/