【问题标题】:How to find path of file outside the working directory dynamically?如何动态查找工作目录外的文件路径?
【发布时间】:2021-10-23 13:25:29
【问题描述】:

我正在开发一个应用程序,其中有包含计算历史的数据库文件,我需要访问它以便用户可以查看数据。但是如果用户移动了数据库文件呢?然后应用程序将无法找到它,因为路径会改变。那么,当文件可以在计算机中的任何位置时,我如何才能找到路径。

【问题讨论】:

  • 数据库是否与文件在同一相对位置?
  • 您别无选择,只能搜索整个文件系统。那么您可能会遇到 2 个或更多同名文件的问题
  • @PeterMoore 是的,但只有在我测试应用程序时,我知道我无法更改数据库的位置。问题是我 100% 肯定有人最终会移动它,但他们无法理解为什么应用程序突然无法运行。
  • 既然“用户”移动了文件并且“用户”使用了该应用程序,那么在您提醒“用户”路径未找到后让用户告诉您它在哪里。

标签: python path


【解决方案1】:

在 Linux 计算机上查找文件的方法是使用命令 findfind <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 的最佳补充之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多