Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何查找目录中具有特定后缀的文件数?_Python_Python 3.x - Fatal编程技术网

Python 如何查找目录中具有特定后缀的文件数?

Python 如何查找目录中具有特定后缀的文件数?,python,python-3.x,Python,Python 3.x,我需要搜索目录并显示文本*.txt文件的数量。在研究中,我相当肯定我可以使用glob和os,但我对如何开始有点不知所措 您可以使用os.listdir 希望这能有所帮助,我会尝试以下方法: import glob import os def fileCount(): myFiles = dict() directory = "C:\somefolder\someotherfolder" for file in glob.glob("*"): if os

我需要搜索目录并显示文本*.txt文件的数量。在研究中,我相当肯定我可以使用glob和os,但我对如何开始有点不知所措

您可以使用os.listdir


希望这能有所帮助,

我会尝试以下方法:

import glob
import os

def fileCount():
    myFiles = dict()
    directory = "C:\somefolder\someotherfolder"

    for file in glob.glob("*"):
        if os.path.isfile(file):
            name, extension = os.path.splitext(file)
            myFiles[extension] = myFiles.get(extension, 0) + 1
            print(os.getcwd())
            os.chdir(directory)
            print('after chdir', os.getcwd())

    return myFiles

if __name__ == "__main__":
    files = fileCount()
    print(files)
glob.glob*:中的文件行将读取指定目录中的所有文件。 行名extension=os.path.splitextfile将把文件名和扩展名拆分为两个对象,但仅当对象是文件而不是另一个文件夹时


希望这有助于开始学习Python。
import glob
import os

def fileCount():
    myFiles = dict()
    directory = "C:\somefolder\someotherfolder"

    for file in glob.glob("*"):
        if os.path.isfile(file):
            name, extension = os.path.splitext(file)
            myFiles[extension] = myFiles.get(extension, 0) + 1
            print(os.getcwd())
            os.chdir(directory)
            print('after chdir', os.getcwd())

    return myFiles

if __name__ == "__main__":
    files = fileCount()
    print(files)