我是python的新手.我需要遍历给定目录的子目录并返回包含特定字符串的所有文件.
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith((".sql")):
if 'gen_dts' in open(name).read():
print name
Run Code Online (Sandbox Code Playgroud)
这是我得到的最接近的.
我得到的语法错误是
Traceback (most recent call last):
File "<pyshell#77>", line 4, in <module>
if 'gen_dts' in open(name).read():
IOError: [Errno 2] No such file or directory: 'dq_offer_desc_bad_pkey_vw.sql'
Run Code Online (Sandbox Code Playgroud)
'dq_offer_desc_bad_pkey_vw.sql'文件中不包含'gen_dts'.
我提前感谢你的帮助.
您收到该错误是因为您正在尝试打开name,这只是文件的名称,而不是它的完整相对路径.你需要做的是open(os.path.join(root, name), 'r')(我添加了模式,因为这是一个很好的做法).
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith('.sql'):
filepath = os.path.join(root, name)
if 'gen_dts' in open(filepath, 'r').read():
print filepath
Run Code Online (Sandbox Code Playgroud)
os.walk()返回一个生成器,让你像元组(root, dirs, files),其中root是当前目录,dirs并且files是目录和文件,分别是根目录的名称.请注意,它们是名称,而不是路径; 或者确切地说,它们是该目录/文件相对于当前根目录的路径,这是另一种说法相同的方式.想起来的另一种方式是,在目录和文件dirs,并files绝不会在他们的斜线.
最后一点; 根目录路径始终以您传递给的路径开头os.walk(),无论它是否与您当前的工作目录相关.所以,因为os.walk('three'),root第一个元组将是'three'(因为os.walk('three/'),它将是'three/').因为os.walk('../two/three'),它会'../two/three'.因为os.walk('/one/two/three/'),它会是'/one/two/three/'; 第二个可能是'/one/two/three/four'.