【问题标题】:Delete files in python that contain a number anywhere in the file name删除python中文件名中任何位置包含数字的文件
【发布时间】:2015-12-27 07:13:33
【问题描述】:

我有一个包含 .jpg 文件的目录,我需要删除该目录中所有文件名中包含数字的文件。

我使用 os.listdir 来指定路径。然后我可以使用 fnmatch.fnmatch 仅删除特定的内容,例如“3453.jpg”,但我需要它来删除 thomas9.jpg 或 thom43as.jpg 之类的内容。基本上任何包含数字的文件名都需要删除。

谢谢, 汤姆

【问题讨论】:

  • 你能发布你到目前为止尝试过的东西吗?
  • 我建议你使用正则表达式(模块re)来检查文件名是否包含数字。类似.*[0-9]+.*

标签: python


【解决方案1】:

使用re 模块。

import os
import re


for _file in os.listdir('.'):
    if re.search('\d.*\.jpg$', _file):
        print(_file)

【讨论】:

  • 如果使用了诸如r'\d.*\.jpg$' 这样的正则表达式模式,则不需要_file.split()
  • @zetysz: \d 足以匹配。前导 .* 不是必需的,因为您使用的是 re.search()。试试看。
【解决方案2】:

使用glob()/iglob() 比使用正则表达式稍微容易一些:

import glob
import os

def delete_files(path, pattern):
    for f in glob.iglob(os.path.join(path, pattern)):
        try:
            os.remove(f)
        except OSError as exc:
            print exc

>>> delete_files('/tmp', '*[0-9]*.jpg')

os.remove() 应在 try/except 块内调用,以防文件无法删除,例如权限不足,正在被其他进程使用,文件是目录等。

使用正则表达式,如果有很多文件,可能值得在循环外编译模式:

import os
import re

def delete_files(path, pattern):
    pattern = re.compile(pattern)
    for f in os.listdir(path):
        if pattern.search(f):
            try:
                os.remove(os.path.join(path, f))
            except OSError as exc:
                print exc

delete_files('/tmp', r'\d.*\.jpg$')

【讨论】:

  • @zetysz:不,没错。一位数字后跟零个或多个字符(可能包括其他数字)。这是可以的,因为re.search() 匹配字符串中的任何位置,尽管指定更完整的模式(例如匹配行首的^.*\d.*\.jpg$)并没有什么坏处。
  • 哦,您删除了有关正则表达式模式的无效评论。但是你是对的,文件不能总是被删除(除非路径与当前目录相同)。固定。
【解决方案3】:

regex 在您的情况下并不是真正需要的,如果您想删除文件名包含任何数字的任何文件,那么您可以这样做:

import os

my_path = 'path_to_your_directory'
any_digit = '1234567890'

os.chdir(my_path) #Just to be sure you are in your working directory not else where!

for f in os.listdir('.'):
    if any(x in f for x in any_digit) and f.endswith('.jpg'):
        os.remove(f)

你也可以使用string模块然后:

import os
import string

my_path = 'path_to_your_directory'

os.chdir(my_path) #Just to be sure you are in your working directory not else where!

for f in os.listdir('.'):
    if any(x in f for x in string.digits) and f.endswith('.jpg'):
        os.remove(f)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 2020-12-23
    • 2023-01-10
    • 1970-01-01
    • 2013-06-30
    • 2011-05-30
    • 2017-01-13
    相关资源
    最近更新 更多