[英]listing csv files using python re.match
I have created a small code in python to list csv files in the current directory: 我在python中创建了一个小代码来列出当前目录中的csv文件:
>>> for i in range(len(os.listdir())):
... isMatch = re.search(r'\.csv$', os.listdir()[i])
... if (isMatch):
... print(os.listdir()[i])
...
HR_data.csv
HR_data2.csv
HR_data_WEKA.csv
WholesaleCustomersData.csv
>>>
Is there a more elegant and shorter way to do this, like using lambda expressions??? 有没有更优雅,更短的方法来执行此操作,例如使用lambda表达式? Thanks very much./
非常感谢。/
You don't need regex, and glob
has overhead. 您不需要正则表达式,并且
glob
有开销。 Just use the inbuilt str.endswith
function: 只需使用内置的
str.endswith
函数:
for filename in os.listdir():
if filename.endswith('.csv'):
print(filename)
Also, it is more efficient to iterate over the elements in a list directly than iterating over the indices and then referencing the list. 同样,直接遍历列表中的元素比遍历索引然后引用列表更有效。 Especially when you consider, you keep calling
os.listdir()
everytime you want to access the ith
file, which is extremely wasteful. 尤其是考虑到这一点时,每次要访问
ith
文件时,都会一直调用os.listdir()
,这非常浪费。
Here's an elegant alternative with filter
: 这是
filter
的一个优雅替代品:
for csv_files in filter(lambda x: x.endswith('.csv'), os.listdir()):
print(csv_files)
Works on both python2.x and 3.x. 适用于python2.x和3.x。
from glob import glob
for f in glob('*.csv'):
print(f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.