Skip to main content
 首页 » 编程设计

python之如何检查python目录中是否只存在txt文件

2025年05月04日15zhengyun_ustc

我必须在 while 循环中检查。我发现以下代码显示了没有 while 循环的文件。

for file in glob.glob("*.txt"): 
    print(file) 

但是如果我使用下面的代码,它在 while 循环中不起作用

a = os.listdir(my_path) 
#print(a) 
for file in glob.glob("*.txt"): 
    print(file) 

我正在尝试使用 OS 模块在 python 中编写一个 watcher 类型

请您参考如下方法:

while True: 
    f = os.listdir(path) 
    if len(f) > 0: 
        for i in os.listdir(path): 
            if i.endswith('.txt'): 
                continue 
            else: 
                dosomething() 
    time.sleep(5) #so loop checks files every 5 sec 

这样你只使用 os 模块,不需要 glob。