简体   繁体   中英

How can I check if only txt file exists in a directory with python?

I have to check in a while loop. I have found the following code it shows the file without while loop.

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

but it does not work in a while loop if i use the following code

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

I am trying to program a watcher type in python with OS module

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

This way you only use os module, glob's not needed.

  • use os.listdir to get all files in a folder
  • len to get total files
  • list comprehension with sum and str.endswith to get count files ending with ".txt"

Demo:

import os
a = os.listdir(my_path)
if len(a) == sum(1 for i in a if i.endswith(".txt")):
    print("All Text")
import os
dr = os.listdir(my_path)
if len(dr) == len(filename for filename, file_extension in a if file_extension == '.txt')):
    #do stuff
    pass

Well, from what i can understand, what you want is to create a watcher service to provide you if a new file is created.

`
import glob
files = glob.glob("*.txt") # Check first time all the files
while True: # till you exit
    _old_files_count = len(files)  # Get count of files
    files = glob.glob("*.txt")
    if len(files) > _old_files_count:   # If new file is created.
        print(*files[_old_files_count:], sep="\n") # Printing all new files in new line.
`

It will provide you with new files created in that particular directory. Also, with some tweaks you can also get files which are deleted. Hope it helps. For using os, just use below instead of glob line.

import os
files = [file for file in os.listdir() if file.endswith("*.txt")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM