I want to find a .txt file in the directory

Asked 2 years ago, Updated 2 years ago, 147 views

How do I find only .txt files in a directory?

python file-io

2022-09-22 22:34

1 Answers

glob.glob(patchname) returns a list of files corresponding to patchname.

import glob
Import os #Write only if you need to change the directory
os.chdir("/mydir") #Write only if you need to change the directory
for file in glob.glob("*.txt"): #'*' means all values
    print(file)

os.listdir(path) returns a list of names in the directory given by path.

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"): #Ended with ".txt"
        print(file)


2022-09-22 22:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.