我正在循环浏览带有以下内容的文件:
PROGDIR=/this/is/a/file/path
LOGDIR=/this/is/another/path
我只是想找到具有路径的第一行(此示例为progdir)。我确定该行是否为路径的方法是,是否具有多个正斜杠。也许有更好的方法可以做到这一点?
我认为与此类似的东西应该起作用:
re.compile('[/]+')
or
a = [line for line in line if '/' in line]
我一直死胡同。有帮助吗?
答案 0 :(得分:2)
答案 1 :(得分:2)
您可以使用count
来做到这一点,例如:
data = ["PROGDIR=/this/is/a/file/path",
"LOGDIR=/this/is/another/path",
"TEST=/xxx.p",
"TEST2=/nsdjsal"]
def get_first_file(lines: list) -> str:
for line in lines:
if line.count("/") > 1:
return line
return ""
print(get_first_file(data))
输出:
"PROGDIR=/this/is/a/file/path"
答案 2 :(得分:0)
与其使用正则表达式,您还可以查看 Python 是否认为它是一条路径。假设文件被读入为 foo
:
split = re.split(r'[\n=]', foo)
paths = list(filter(lambda x: os.path.isabs(x), split))
这适用于问题中的示例,因为 isabs
(与 isdir
或 isfile
不同)实际上并不检查该路径是否有任何东西。