Python的re.findAll()函数无法按预期工作

时间:2018-06-23 10:39:06

标签: python regex

我正在尝试创建一个python脚本,该脚本将从具有特定名称模式的工作目录中查找所有文件。

我已将所有文件存储在列表中,然后尝试在列表上应用re.findall方法以仅获取具有该名称模式的文件列表。

我已经编写了这段代码:

# Create the regex object that we will use to find our files
fileRegex = re.compile(r'A[0-9]*[a-z]*[0-9]*.*')
all_files = []

# Recursevly read the contents of the working_dir/Main folder #:
for folderName, subfolders, filenames in os.walk(working_directory + "/Main"):
    for filename in filenames:
        all_files.append(filename)

found_files = fileRegex.findall(all_files)

我在代码的最后一行收到此错误:

TypeError: expected string or bytes-like object

我也尝试过re.findall(all_files)而不是使用在该行之前创建的'fileRegex'。同样的错误。请告诉我我在做什么错。非常感谢您阅读我的帖子!

编辑(第二个问题): 我遵循了答案,现在一切正常。找到文件后,我正在尝试使用与该模式匹配的文件来创建档案。归档文件是按我编写代码的方式创建的,整个文件路径包含在归档文件中(从/到文件的所有文件夹)。我只希望文件包含在最终的.zip文件中,而不是构成路径的整个目录和子目录中。

这是代码。 .zipfile的生成在底部。请给我一个提示,我如何解决这个问题?我尝试了很多事情,但没有任何效果。谢谢:

# Project properties:

#  Recursively read the contents of the 'Main' folder which contains files with different names.
#  Select only the files whose name begin with letter A and contain digits in it. Use regexes for this.
#  Archive these files in a folder named 'Created_Archive' in the project directory. Give the archive a name of your choosing.


# Files that you should find are:
  # Aerials3.txt, Albert0512.txt, Alberto1341.txt


########################################################################################################################################
import os
import re
import zipfile
from pathlib import Path

# Get to the proper working directory
working_directory = os.getcwd()
if working_directory != "/home/paul/Desktop/Python_Tutorials/Projects/Files_And_Archive":
  working_directory = "/home/paul/Desktop/Python_Tutorials/Projects/Files_And_Archive"
  os.chdir(working_directory)

check_archive = Path(os.getcwd() + "/" + "files.zip")
if check_archive.is_file():
    print("Yes. Deleting it and creating it.")
    os.unlink(os.getcwd() + "/" + "files.zip")
else:
    print("No. Creating it.")

# Create the regex object that we will use to find our files
fileRegex = re.compile(r'A[0-9]*[a-z]*[0-9]+.*')
found_files = []

# Create the zipfile object that we will use to create our archive
fileArchive = zipfile.ZipFile('files.zip', 'a')

# Recursevly read the contents of the working_dir/Main folder #:
for folderName, subfolders, filenames in os.walk(working_directory + "/Main"):
    for filename in filenames:
        if fileRegex.match(filename):
            found_files.append(folderName + "/" + filename)

# Check all files have been found and create the archive. If the archive already exists
# delete it.


for file in found_files:
    print(file)
    fileArchive.write(file, compress_type=zipfile.ZIP_DEFLATED)

fileArchive.close()

3 个答案:

答案 0 :(得分:3)

re.findAll适用于不在列表中的字符串,因此最好在列表中使用r.match来过滤实际匹配的字符串:

found_files = [s for s in all_files if fileRegex.match(s)]

答案 1 :(得分:1)

regex适用于字符串而不是列表。以下作品

import re
import os

# Create the regex object that we will use to find our files
# fileRegex = re.compile(r'A[0-9]*[a-z]*[0-9]*.*')
fileRegex = re.compile(r'.*\.py')
all_files = []
found_files = []

working_directory = r"C:\Users\michael\PycharmProjects\work"

# Recursevly read the contents of the working_dir/Main folder #:
for folderName, subfolders, filenames in os.walk(working_directory):
    for filename in filenames:
        all_files.append(filename)
        if fileRegex.search(filename):
            found_files.append(filename)

print('all files\n', all_files)
print('\nfound files\n', found_files)

答案 2 :(得分:0)

re.findall不包含字符串列表。您需要re.match

# Create the regex object that we will use to find our files
fileRegex = re.compile(r'A[0-9]*[a-z]*[0-9]*.*')
all_files = []

# Recursively read the contents of the working_dir/Main folder #:
for folderName, subfolders, filenames in os.walk(working_directory + "/Main"):
    for filename in filenames:
        all_files.append(filename)

found_files = [file_name for file_name in all_files if fileRegex.match(file_name)]