如何用python选定文件夹_Python 3.5 OS.Walk用于选定的文件夹并包括其子文件夹

I'm writing a python script where I search a specific string across a tree directory. I ask the end-user to define which folders they would like to include in the search, and once the script finds one of the folders that the user would like to scan, the script is supposed to also scan all the sub-folders for this selected folder.

I'm trying to do a couple of for loops, but I can't get it to work.

The beginning of the script looks like:

startTime = datetime.datetime.now()

option = input("Do you want to scan: A) Excel B) PDF C) Both Q) Quit: ")

option = option.lower()

if (option == "b") or (option == "b") or (option == "c"):

stringToSearch = input("Which string do you want to search? ")

folderToSearch = input("Which top folder to search from(i.e. Z:\S 15\BOMs)? ")

subfoldersToSearch = input("Which subfolders(i.e. BOMs, Catalogs?

print("Press CTRL + C to stop the search")

for foldername, subfolders, filenames in os.walk(folderToSearch):

for filename in filenames:

if (subfoldersToSearch == "") or (subfoldersToSearch in foldername):

print(subfoldersToSearch, "+++", foldername)

for x_foldername, x_subfolders, x_filenames in os.walk(foldername):

totalFiles += 1

for x_filename in x_filenames:

if (x_filename.endswith('.pdf') and option == "b") or (x_filename.endswith('.pdf') and option == "c"):

[Do remaining stuff]

The problem is that it gets into a continuous loop because as soon as it's done walking through one of the selected folders, it comes back to the first for loop and it tries to walk the same selected folder again.

Is there a better way to do this os.walk?

Basically, I would like the script to find a specific folder and then scan the contents of that folder (including folders), and then to keep going to the next folder without starting all over again.

解决方案

I figured it out and it actually works well with just one for loop. Here is how the new code looks and hope it will help someone in the future...Best

startTime = datetime.datetime.now()

option = input("Do you want to scan: A) Excel B) PDF C) Both Q) Quit: ")

option = option.lower()

if (option == "b") or (option == "b") or (option == "c"):

stringToSearch = input("Which string do you want to search? ")

folderToSearch = input("Which top folder to search from(i.e. Z:\S 15\BOMs)? ")

subfoldersToSearch = input("Which subfolders(i.e. BOMs, Catalogs?

print("Press CTRL + C to stop the search")

for foldername, subfolders, filenames in os.walk(folderToSearch, topdown=True):

print(subfolders)

for filename in filenames:

if (subfoldersToSearch == "") or (subfoldersToSearch in foldername):

print(subfoldersToSearch, "+++", foldername)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值