Getting Every File in a Windows Directory

后端 未结 5 1760
囚心锁ツ
囚心锁ツ 2020-12-24 07:31

I have a folder in Windows 7 which contains multiple .txt files. How would one get every file in said directory as a list?

5条回答
  •  爱一瞬间的悲伤
    2020-12-24 07:51

    You can use os.listdir(".") to list the contents of the current directory ("."):

    for name in os.listdir("."):
        if name.endswith(".txt"):
            print(name)
    

    If you want the whole list as a Python list, use a list comprehension:

    a = [name for name in os.listdir(".") if name.endswith(".txt")]
    

提交回复
热议问题