python 在python中,如果文件以一组特定的字母开头,如何从循环中排除文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2193710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:00:55  来源:igfitidea点击:

In python, how do I exclude files from a loop if they begin with a specific set of letters?

pythonstring

提问by Ruth

I'm writing a Python script that goes through a directory and gathers certain files, but there are a number of files I want excluded that all start the same.

我正在编写一个 Python 脚本,它遍历一个目录并收集某些文件,但是我想排除许多文件,它们都以相同的方式开始。

Example code:

示例代码:

for name in files:
   if name != "doc1.html" and name != "doc2.html" and name != "doc3.html":
      print name

Let's say there are 100 hundred HTML files in the directory all beginning with 'doc'. What would be the easiest way to exclude them?

假设目录中有 10000 个 HTML 文件都以 .html 开头'doc'。排除它们的最简单方法是什么?

Sorry I'm new to Python, I know this is probably basic.

抱歉,我是 Python 新手,我知道这可能是基本的。

Thanks in advance.

提前致谢。

回答by Nadia Alramli

if not name.startswith('doc'):
     print name

If you have more prefixes to exclude you can even do this:

如果您要排除更多前缀,您甚至可以这样做:

if not name.startswith(('prefix', 'another', 'yetanother')):
     print name

startswithcan accept a tuple of prefixes.

startswith可以接受前缀元组。

回答by Karmic Coder

for name in files:
    if not name.startswith("doc"):
        print name

回答by Troy J. Farrell

If you find functional programming matches your style better, Python makes it simple to filter lists with the filter() function:

如果您发现函数式编程更符合您的风格,Python 可以使用 filter() 函数轻松过滤列表:

>>> files = ["doc1.html", "doc2.html", "doc3.html", "index.html", "image.jpeg"]
>>> filter_function = lambda name: not name.startswith("doc")
>>> filter(filter_function, files)
['index.html', 'image.jpeg']

Also take a look at apply(), map(), reduce(), and zip().

还可以看看 apply()、map()、reduce() 和 zip()。

回答by Roman A. Taycher

looks like this problem might be a better fit for list stuff so like Troy said (Although I prefer putting the function directly into the filter)

看起来这个问题可能更适合像 Troy 所说的列表内容(尽管我更喜欢将函数直接放入过滤器中)

filter(lambda filename: not filename.startswith("doc"),files)

or

或者

[filename for filename in files if not filename.startswith("doc")]

回答by Josh Wright

You could also use a list comprehension.

您还可以使用列表理解

cleaned_list = [filename for filename in files if not filename.startswith('doc')]

回答by Kurt Campher

This is my 2 cents:
A bit of list comprehension.It's always better for effeciency.

这是我的 2 美分:
有点列表理解。它总是更好的效率。

file_list = [file for file in directory if not file.startswith(("name1", "name2", "name3"))]

回答by ghostdog74

import os
os.chdir("/home")
for file in os.listdir("."):
   if os.path.isfile(file) and not file.startswith("doc"):
      print file

回答by Azhar Ansari

Skip the files that you want to exclude while iterating over all the files present in the folder. Below code would skip all the html files that start with 'doc'

在迭代文件夹中存在的所有文件时跳过要排除的文件。下面的代码将跳过所有以“doc”开头的 html 文件

import glob
import re
for file in glob.glob('*.html'):
    if re.match('doc.*\.html',file):
        continue
    else:
        #do your stuff here
        print(file)

回答by tzot

An alternate take to a functional solution to this issue, with the advantage of using recent additions to the standard library (using the same example filenames as Troy J. Farrell in another answer) :

对此问题的功能性解决方案的另一种选择,其优点是使用标准库中最近添加的内容(在另一个答案中使用与 Troy J. Farrell 相同的示例文件名):

>>> import operator, itertools
>>> filter_fun= operator.methodcaller("startswith", "doc")
>>> files = ["doc1.html", "doc2.html", "doc3.html", "index.html", "image.jpeg"]
>>> list(itertools.ifilterfalse(filter_fun, files))
['index.html', 'image.jpeg']

operator.methodcallercalled with methodname, [optional arguments]returns a function that, when called with an object objas its argument, returns the result of obj.methodname(optional_arguments). itertools.ifilterfalse, unlike filter, returns an iterator instead of a list and the filter decision is negated.

operator.methodcaller调用 withmethodname, [optional arguments]返回一个函数,当调用一个对象obj作为其参数时,返回 的结果obj.methodname(optional_arguments)itertools.ifilterfalse与 不同filter,它返回一个迭代器而不是一个列表,并且过滤器决定被否定。

回答by Stefano Borini

for name in files:
    if name[0:3] == "doc":
         continue