简体   繁体   English

在Python目录中搜索.txt,.scv文件

[英]Search for .txt, .scv files in directory in Python

I would like to add in a list all the files with an extension .txt and .scv in a given directory in Python. 我想在Python的给定目录中将所有扩展名为.txt和.scv的文件添加到列表中。 My current code looks like this: 我当前的代码如下所示:

import glob
def core():
  old_path = '/home/demo/'
  files = glob.glob(old_path+(*.{txt, scv}))
  print(len(files))

but it doesn't work. 但这不起作用。

There is a syntax error in your code - wildcards must be strings. 您的代码中存在语法错误-通配符必须为字符串。 And the second problem is that glob doesn't support brace expansion (ie it doesn't understand {txt, csv} ). 第二个问题是glob不支持花括号扩展(即,它不理解{txt, csv} )。 So you need to use basic wildcards: 因此,您需要使用基本的通配符:

import glob
def core():
    old_path = '/home/demo/'
    txt_files = glob.glob(old_path+'*.txt')
    csv_files = glob.glob(old_path+'*.csv')
    print(len(txt_files + csv_files))

core()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM