通过一个 int数字获取文件路径下所有包含该数字的路径
时间: 2024-04-22 10:24:22 浏览: 6
要通过一个整数数字获取文件路径下所有包含该数字的路径,您可以使用递归的方式遍历文件系统中的所有文件和文件夹,并在遍历过程中判断路径中是否包含该数字。
以下是一个示例代码,假设您有一个名为root_path的文件夹路径和一个名为target_num的整数,想要获取包含该数字的所有路径:
```python
import os
def find_paths_with_number(root_path, target_num):
matching_paths = []
# 遍历文件夹中的所有内容,包括子文件夹和文件
for root, dirs, files in os.walk(root_path):
# 遍历当前文件夹中的子文件夹
for dir in dirs:
dir_path = os.path.join(root, dir)
# 检查路径中是否包含目标数字
if str(target_num) in dir_path:
matching_paths.append(dir_path)
# 遍历当前文件夹中的文件
for file in files:
file_path = os.path.join(root, file)
# 检查路径中是否包含目标数字
if str(target_num) in file_path:
matching_paths.append(file_path)
return matching_paths
# 示例用法
root_path = 'your/file/path'
target_num = 123
result = find_paths_with_number(root_path, target_num)
print(result)
```
在上述示例中,我们使用了`os.walk`函数来遍历文件夹中的所有内容。对于每个子文件夹和文件,我们检查其路径是否包含目标数字。如果包含,我们将该路径添加到`matching_paths`列表中。最后,我们返回包含目标数字的所有路径。
请注意,上述代码仅是一个示例,您可能需要根据具体情况进行适当的修改。另外,这个查找过程可能会涉及到文件系统的访问权限等问题,请确保您的程序有足够的权限来访问文件路径。