You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的while循环检测目录中是否存在文件?

解决Python循环检测目录文件的问题

你要实现的是循环检测指定目录是否存在目标.sql文件,原代码的while循环存在语法错误,且缺少具体的文件检测逻辑,下面是修正后的完整实现:

关键问题修正

  1. Python的while循环语法是while 条件:,没有while ... do :这种写法
  2. 需要明确检测目录中是否存在目标文件的逻辑(比如后缀为.sql的文件)
  3. 循环必须加入延迟,避免持续占用系统CPU资源

完整代码实现

import os
import datetime
import time
# 假设tools是你已导入的自定义模块

root_path = 'C:/Users/Desktop/Files/'
date_now = datetime.datetime.now().strftime("%Y%m%d")

# 封装检测目录中是否存在.sql文件的函数
def has_sql_files(path):
    # 遍历目录文件,判断是否有.sql后缀的文件
    for filename in os.listdir(path):
        if filename.endswith('.sql'):
            return True
    # 也可以用glob模块简化(需先import glob):
    # return len(glob.glob(os.path.join(path, '*.sql'))) > 0
    return False

# 初始状态检查
if not has_sql_files(root_path):
    print("目录初始无.sql文件")
else:
    print("目录存在.sql文件,开始执行scp...")
    # 用f-string拼接命令更清晰易读
    cmd = f'scp {root_path}*.sql ...'
    ret1, status1 = tools.cmd(cmd)
    print(f'ret1: {ret1}')

# 循环检测逻辑(带超时控制)
timeout_seconds = 1800  # 设置超时时间为30分钟
start_time = time.time()

while time.time() - start_time < timeout_seconds:
    if has_sql_files(root_path):
        print("检测到目录中的.sql文件!")
        # 执行你需要的操作,比如再次scp
        cmd = f'scp {root_path}*.sql ...'
        ret1, status1 = tools.cmd(cmd)
        print(f'ret1: {ret1}')
        # 如果只需要检测到一次就退出循环,添加break
        break
    print("等待.sql文件中...")
    time.sleep(10)  # 每10秒检测一次,降低资源消耗
else:
    print("超时未检测到.sql文件")

代码说明

  • has_sql_files函数:封装文件检测逻辑,可根据需求修改(比如检测特定日期命名的文件)
  • 超时控制:避免无限循环,可根据实际需求调整timeout_seconds的值
  • time.sleep():控制检测间隔,平衡检测灵敏度和资源占用
  • f-string:替代字符串拼接,提升代码可读性和维护性

内容的提问来源于stack exchange,提问作者Jan Pietruszka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 08:22:30