我多次浏览多个网站,没有其他帖子可以找到我想要的具体内容。
一般的想法是程序搜索整个计算机,跳过任何拒绝访问或以其他方式无法访问的文件夹,用于特定文件,然后返回其位置。 E.g:
def findFile(targetFile):
targetLocation = searchFor(targetFile) in drives.All
OUTPUT:
targetLocation = "D:\SteamLibrary\steamapps\common\Grand Theft Auto V"
OR:
This file exists in two locations:
"D:\SteamLibrary\steamapps\common\Grand Theft Auto V" and "C:\Program Files (x86)\Steam\steamapps\common\Grand Theft Auto V"
Please specify which:
由于
注意:我已经看到了问题/ 1724693 / find-a-file-in-python,它没有回答我的问题。我需要一些可以处理重复项的东西,要求你选择不把它放在数组中
import os
target_filename = "GTA 5.exe"
start_folder = "C:/" #It needs to search every drive (C: D: E: F: etc)
for root, dirs, files in os.walk(start_folder):
if target_filename in files:
print(root + '\\' + target_filename )
输出如下:
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
================== RESTART: C:/Users/Redacted/Desktop/test.py ==================
>>>
答案 0 :(得分:0)
如果您知道文件名(假定为target_filename)和起始文件夹(假设为start_folder),您想使用os.walk查找重复项:
import os
for root, dirs, files in os.walk(start_folder):
if target_filename in files:
print(root + '\\' + target_filename )