我有几个 python 文件,我想在不同的目录中运行,它将从 100 多个文件中搜索特定的模式。假设我在 /home/jay 目录中有 python 文件,并且在 /home/jay/data 目录中有 100 多个文件。
我该怎么做才能实现这一目标?
我的 python 代码是:
import re
import os
os.chdir(r'/home/jay/data/')
files = open('*')
for line in files :
line = line.rstrip()
if re.search('Model' , line):
print(line)
我遇到以下错误:
Traceback (most recent call last):
File "/home/jay/test.py", line 4, in ?
files = open('*')
IOError: [Errno 2] No such file or directory: '*'
请您参考如下方法:
您正在寻找os.listdir .它将为您提供指定目录中所有文件名的列表,默认为当前目录。 '*' 不起作用的原因是它是由您的 shell 扩展的命令行结构。您只能在支持这种扩展的 shell 或脚本中真正使用它。由于 open 不通过 shell,它会尝试查找实际名为 * 的文件。此外,open 一次只能处理一个文件。
import os, os.path, re
os.chdir(r'/home/jay/data/')
files = os.listdir()
for name in files:
# Skip directories
if os.path.isdir(name):
continue
with open(name) as file:
for line in file:
line = line.rstrip()
if re.search('Model' , line):
print(line)
That being said, as a matter of personal preference, I generally avoid using os.chdir. Instead, I prefer specifying full paths using os.path.join. Here is your example rewritten to do that:
from os import listdir
from os.path import join, isdir
folder = '/home/jay/data'
files = listdir(folder)
for name in files:
name = join(folder, name)
# Skip directories
if isdir(name):
continue
with open(name) as file:
for line in file:
line = line.rstrip()
if 'Model' in line:
print(line)
我冒昧地完全删除了正则表达式,因为它只会在你有很多文件时减慢速度。如果你确实在一些更复杂的场景中使用正则表达式,在你使用它之前使用 re.compile 编译 if .
此外,如果需要,您可以在此处自由使用相对路径。例如,如果您总是从 /home/jay 运行,则可以设置 folder = 'data' 而不是 folder = '/home/jay/data ' 在第二个例子中。
