如何在 Python 中列出以“2019_03”开头且扩展名为“.text”的文件
How to list a file starting with "2019_03" with extension ".text" in Python
我在 linux 系统中有很多这样的文件:
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
.
我只想在 python 中列出以“2019_03”开头且扩展名为“.text”的列表。我运行在linux终端的命令如下:
ls /path/[2019_03]* | grep /*.text
我如何在 python 中执行此操作?
glob 模块将成为您的朋友。
import glob
list_of_files = glob.glob('/path/2019_03*.text')
您可以简单地使用 python (re) 中的正则表达式库,然后搜索“.text”。要获取文件列表,我们可以使用os模块来列出文件:
# ~ 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)]
我在 linux 系统中有很多这样的文件:
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
.
我只想在 python 中列出以“2019_03”开头且扩展名为“.text”的列表。我运行在linux终端的命令如下:
ls /path/[2019_03]* | grep /*.text
我如何在 python 中执行此操作?
glob 模块将成为您的朋友。
import glob
list_of_files = glob.glob('/path/2019_03*.text')
您可以简单地使用 python (re) 中的正则表达式库,然后搜索“.text”。要获取文件列表,我们可以使用os模块来列出文件:
# ~ 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)]