-1

I have many file in a linux system some like this:

2019_03_01.text
2019_03_01.jpg
2019_03_01.png
2019_03_02.text
2019_03_02.jpg
2019_03_02.png
...
.
2019_09_21.text
2019_09_21.jpg
2019_09_21.png
.

I want to list only starting "2019_03" with extension ".text " in python. I run the command on the linux terminal as follows:

ls /path/[2019_03]* | grep /*.text

How can i do this in python?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
SAFAK
  • 59
  • 8

2 Answers2

1

The glob module will be your friend.

import glob

list_of_files = glob.glob('/path/2019_03*.text')
0

You can simply use the regex library in python (re), and search for '.text'. To get the list of files, we can use the os module to list the files:

# ~ Libraries ~ #
import os
import re

# ~ Directory ~ #
path_to_directory = '/path/to/directory/'

# ~ List of files ~ #
file_list = os.listdir(path_to_dir)

# ~ Get only files with .text extensions ~ #
file_text = [x for x in file_list if re.search('.text',x)]

Ryan
  • 113
  • 1
  • 7