jone kim
jone kim

Reputation: 51

Get the list of all the files with ".txt" after changing the current working directory

I changed the current working directory and then I want to list all the files in that directory with extension .txt. How can I achieve this?

# !/usr/bin/python

import os

path = "/home/pawn/Desktop/projects_files"
os.chdir(path)

## checking working directory
print ("working directory "+ os.getcwd()+'\n')

Now how to list all the files in the current directory (projects_files) with extension .txt?

Upvotes: 2

Views: 78

Answers (4)

Elisha
Elisha

Reputation: 4951

if you don't want to import glob as suggested in the other good answers here, you can also do it with the same os moudle:

path = "/home/pawn/Desktop/projects_files"    
[f for f in os.listdir(path) if f.endswith('.txt')]

Upvotes: 0

Avinash Babu
Avinash Babu

Reputation: 6252

You would need to use glob in python.

It will help you to fetch the files of a particular format..

Usage

>>> import glob
>>> glob.glob('*.gif')

Check the documentation for more details

Upvotes: 0

Jose Varez
Jose Varez

Reputation: 2077

You can use glob. With glob you can use wildcards as you would do in your system command line. For example:

import glob
print( glob.glob('*.txt') )

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174624

Use glob, which is a wildcard search for files, and you don't need to change the directory either:

import glob

for f in glob.iglob('/home/pawn/Desktop/project_files/*.txt'):
   print(f)

Upvotes: 2

Related Questions