[英]Find files of the same type in the same directory with Python
Is there a way to find all the files of a particular file type that is specified and recursively call them to be read until you have read all of the files? 有没有一种方法可以找到指定的特定文件类型的所有文件,然后递归调用它们以进行读取,直到您读取所有文件为止? (This is in Ubuntu)
(这是在Ubuntu中)
For example: 例如:
In directory /home
you have files a.png
, b.txt
, c.txt
, d.txt
, e.jpeg
and I would like to read all the file that are txt
. 在
/home
目录中,您有a.png
, b.txt
, c.txt
, d.txt
, e.jpeg
,我想读取所有txt
文件。
How would one do so in Python? 如何在Python中做到这一点?
Sub Question: Is it possible to do what was mentioned above with two different file types? 子问题:是否可以对两种不同的文件类型执行上述操作?
You could use glob.glob()
to do this: 您可以使用
glob.glob()
执行此操作:
>>> from glob import glob
>>> glob('/home/*.txt')
['/home/c.txt', '/home/d.txt', '/home/b.txt']
>>> [glob(i) for i in ['/home/*.txt', '/home/*.jpeg']]
[['/home/c.txt', '/home/d.txt', '/home/b.txt'], ['/home/e.jpeg']]
>>>
Assuming you're using the extension of the file to guess the type, you could use os.listdir and filter the files based on the filename: 假设您使用文件扩展名猜测类型,则可以使用os.listdir并根据文件名过滤文件:
import os
for filename in os.listdir('.'):
if filename.endswith('.txt'):
# Do what you want to do
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.