简体   繁体   中英

python count number of text file in certain directory

I am trying to get the number of the files in a certain directory, but I want it to count only text file because I have another directory in the accounts and DS. Store file. What should I modify to only get the number of text files?

list = os.listdir("data/accounts/")
number_files = len(list)
print(number_files)

From Count number of files with certain extension in Python ,

Solution 1.

fileCounter = 0
for root, dirs, files in os.walk("data/accounts/"):
    for file in files:    
        if file.endswith('.txt'):
            fileCounter += 1

Solution 2.

fileCounter = len(glob.glob1("data/accounts/","*.txt"))

Read about glob here here

Assuming your text files end in ".txt", you could use something like:

files = [x for x in os.listdir("data/accounts/") if (os.isfile(x) and x.endswith('.txt'))]
number_files = len(list)
print(number_files)

Using os.isfile() to ignore directories and string.endswith() to determine text file-ness.

An alternative module that may work for you is glob .

It will allow you to use wildcards so you can capture just the files you are interested in.

from glob import glob
filenames = glob("data/accounts/*.txt")
number_of_files = len(filenames)
print(number_of_files)
number_of_files = sum(f.endswith('.txt') for f in os.listdir("data/accounts/"))

str.endswith() returns True or False
True and False have numeric values of one and zero, respectively.
sum() will consume the generator expression.

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