Python 2.6.6同时打开多文件触发SyntaxError语法错误求助
解决Python 2.6中
with语句同时打开多文件的语法错误 嘿,我一眼就揪出问题根源了——你用的Python 2.6.6版本不支持在单个with语句里同时声明多个上下文管理器(就是你写的那种用逗号分隔多个open()的写法)!这种简洁的多文件打开语法是Python 2.7和Python 3.1之后才引入的新特性,所以在2.6里运行必然会报语法错误。
给你两个可行的解决办法:
方法一:嵌套with语句(首推)
这是最稳妥、兼容性最好的方式,不需要依赖额外模块,逻辑也清晰易懂:
import os path = '/home/test/testData/log/' os.chdir(path) k = 0 word = 'Log ends' filename1 = 'test.log' filename2 = 'tes2.log' # 嵌套with语句,分别管理两个文件资源 with open(filename1) as firstFile: with open(filename2) as secondFile: for line in firstFile: if word in line: print(line)
方法二:使用contextlib.nested(仅作参考,不推荐)
Python 2.6提供了contextlib.nested来实现多上下文管理,但这个函数在Python 2.7已经被弃用,而且存在潜在风险——如果其中一个文件打开失败,可能会导致另一个文件的资源无法正常释放,所以尽量优先用第一种方法:
from contextlib import nested import os path = '/home/test/testData/log/' os.chdir(path) k = 0 word = 'Log ends' filename1 = 'test.log' filename2 = 'tes2.log' with nested(open(filename1), open(filename2)) as (firstFile, secondFile): for line in firstFile: if word in line: print(line)
最后多说一句:Python 2系列已经停止维护很多年了,如果条件允许的话,建议升级到Python 3.x版本,不仅能用上这种简洁的语法,还能获得更多新特性和安全补丁哦。
内容的提问来源于stack exchange,提问作者Kuldeep
相关产品推荐
相关产品推荐

