【问题标题】:Python endswith() function cannot avoid copying .py filePython endswith() 函数无法避免复制 .py 文件
【发布时间】:2014-12-11 13:26:53
【问题描述】:

我正在尝试根据扩展名复制一些文件。我的目标是复制除 ext_to_avoid 变量中的扩展之外的所有内容。但是,我失败了,因为它复制了我不想复制的 .py 文件。我知道 endwith 需要一维变量或元组才能工作。

我的部分脚本如下:

x = os.getcwd()
ext_to_avoid = (".xml", ".bat", ".py", ".txt");
list_of_files_to_copy = []
for root, dirs, files in os.walk(x):
  for name in files:
    if not any([name.endswith(x) for x in ext_to_avoid]):
        print(os.path.join(root,name))
        list_of_files_to_copy.append(os.path.join(root,name))

我不确定它有什么问题。谁能指出我正确的方向?

最诚挚的问候,

【问题讨论】:

  • 你不需要使用分号“;”结束行。
  • 你我的错。更新代码 sn -p :)
  • 我的意思是,它没有“错误”,只是 Python 忽略了末尾的分号。
  • 是的......我没有采用好的做法,我很糟糕,哈哈

标签: python tuples copying


【解决方案1】:

您有许多文件扩展名要检查。由于函数“endswith”接受单个字符串作为参数,给定单个name,您需要针对每个ext 对其进行测试:

matches = False
for ext in ext_to_avoid:
    if name.lower().endswith(ext):
        matches = True
        break
if not matches:
    # ...

更简单的一个班轮可以是:

if not any([name.lower().endswith(ext) for ext in ext_to_avoid]):
    # ...

编辑:嗯,看来str.endswith 也将接受tuple。这意味着您的原始代码是正确的;尝试再次检查小写:

if not name.lower().endswith(ext_to_avoid):
    # ...

【讨论】:

  • 对不起,你的一个班轮不起作用。更新了我的代码 sn-p
  • str.endswith() 也将接受扩展元组。
  • 我知道为什么它不起作用 - 愚蠢的视觉!看了我实际执行脚本的第一行!!!!!! grrr...谢谢@vz0
  • @hagubear 更新了答案。看来你用的是windows,先试试把字符串也转成小写吧。
  • @vz0 别担心。有用!正如我所说,我是个白痴并检查脚本执行的第一行,因此我抱怨 .py 文件。
【解决方案2】:

我刚刚尝试了您的原始代码,它工作正常:

import os

x = os.getcwd()
ext_to_avoid = (".xml", ".bat", ".py", ".txt");
list_of_files_to_copy = [];
for root, dirs, files in os.walk(x):
  for name in files:
    if (name.endswith(ext_to_avoid)) is False:
        print(os.path.join(root,name))
        list_of_files_to_copy.append(os.path.join(root,name))

一个尼特。最好写成:

if not name.endswith(ext_to_avoid):

代替:

if (name.endswith(ext_to_avoid)) is False:

【讨论】:

    【解决方案3】:

    如果你想避免额外的变量使用,你可以这样做:

    for root, dirs, files in os.walk(x):
        for name in files:
            for ext in ext_to_avoid:
                if name.lower().endswith(ext):
                    break
            else:
                 # ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 2021-12-04
      • 1970-01-01
      • 2019-05-30
      相关资源
      最近更新 更多