在 Linux 计算机上查找文件的方法是使用命令 find 和 find <path> -name <filename> 一样
python 你可以用它来调用它
import subprocess
run = subprocess.run(f'find {dirpath} -name {filename}', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if run.returncode
possible_paths = [p for p in run.stdout.splitlines() if "Permission denied" not in p]
如果find 不在计算机上,另一种更便携的方法是使用pathlib 模块,如果你还没有遇到过,你应该学习。然后你会创建一个像这样的 find 命令,它会遍历 dirs 来查找文件名。
from pathlib import Path
def find(dirpath, filename):
matches = []
for p in dirpath.iterdir():
try:
if p.is_dir():
matches.extend( find(p, filename) )
elif p.name == filename:
# is a file
print(p)
matches.append(p)
except PermissionError as e:
print(e)
return matches
etc = Path('/etc/')
file = 'K90network'
print( find(etc, file) )
从中得到的是文件的路径对象。
[PosixPath('/etc/rc.d/rc0.d/K90network'), PosixPath('/etc/rc.d/rc1.d/K90network'), PosixPath('/etc/rc.d/rc6.d/K90network'), PosixPath('/etc/rc0.d/K90network'), PosixPath('/etc/rc1.d/K90network'), PosixPath('/etc/rc6.d/K90network')]
然后你可以把它变成字符串列表或使用该路径对文件进行操作,比如打开它。
编辑:
我更新了这个函数,因为虽然它可以用于hosts 文件,但它没有正确处理权限被拒绝,也没有将更深层调用的结果传回。所以像K90network 这样的文件没有被返回。但现在它可以处理所有这些了。
我还应该指出,在这些路径对象中有一个成员函数samefile(),您可以询问它们是否是同一个文件(如果它们是链接的)。 pathlib.Path 是多年来 IMO 对 python 的最佳补充之一。