简体   繁体   English

python:检查特定字符串是否是文件名的一部分

[英]python: check if a specific string is part of a filename

I have a list, where each entry consists of 5 individual random numbers:我有一个列表,其中每个条目由 5 个单独的随机数组成:

List-output:列表输出:

...
['00349']
['02300']
['00020']
...

Now I have two nested for loops.现在我有两个嵌套的 for 循环。 The outer loop iterates over this list.外部循环遍历这个列表。 The inner loop iterates over a buch of files which are located in a separate directory.内部循环遍历位于单独目录中的大量文件。 The aim is that I want to check each entry in the list if the number is contained in one of the filenames.目的是我想检查列表中的每个条目是否包含在其中一个文件名中。 If so, I want to copy these files into a separate target directory and break the inner loop because the item was found and continue with the next entry in the list.如果是这样,我想将这些文件复制到一个单独的目标目录中并打破内部循环,因为找到该项目并继续列表中的下一个条目。

Structure of a file example:文件结构示例:

name_01043.json

I tried several things (see below) but the following version returns always false.我尝试了几件事(见下文),但以下版本总是返回错误。

Here is my code so far:到目前为止,这是我的代码:

from re import search
import fnmatch

list = []

# some code to fill the list

SOURCE_PATH = "dir/source"
TARGET_PATH = "dir/target"

for item in list:
    for fname in os.listdir(SOURCE_PATH):
        # check if fname contains item name:
        strg1 = str(fname)
        strg2 = str(item)
        if fnmatch.fnmatch(fname, strg2):
        # if fnmatch.fnmatch(fname, '*' + strg2 + '*'):
            sourcepath = os.path.join(SOURCE_PATH, fname)
            shutil.copy(sourcepath, TARGET_PATH)
            break

You can use something like this:你可以使用这样的东西:

for path, subdirs, files in os.walk(SOURCE_PATH):
    for file in files:
        if strg2 in str(file):
            # Do something

This for will return each path, subdirectory and file from the location.这将返回该位置的每个路径、子目录和文件。 You can check file by file this way and simply check if the str(file) contains the string you need您可以通过这种方式逐个文件检查文件,只需检查str(file)是否包含您需要的字符串

Here's an example where you could make good use of the glob module:这是一个可以充分利用 glob 模块的示例:

import glob
import os
import shutil

SOURCE_PATH = 'dir/source'
TARGET_PATH = 'dir/target'
# just use some hard-coded values for the sake of example
mylist = ['00349', '02300', '00020']

for e in mylist:
  for file in glob.glob(os.path.join(SOURCE_PATH, f'*{e}*')):
    shutil.copy(file, TARGET_PATH)

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

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