我正在尝试创建一个python脚本,它将从具有特定名称模式的工作目录中查找所有文件。在
我已经将所有文件存储在一个列表中,然后我尝试应用关于芬德尔方法获取具有该名称模式的文件列表。在
我写了以下代码:
# 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)
我在代码的最后一行得到了这个错误:
^{pr2}$我也试过了关于芬德尔(所有_文件)而不是使用在该行之前创建的“fileRegex”。同样的错误。请告诉我我做错了什么。非常感谢您阅读我的帖子!在
编辑(第二个问题): 我已经找到了答案,现在一切正常。我正在尝试创建一个档案,其中的文件与我找到的模式相匹配。存档是以我编写代码的方式创建的,文件的整个路径都包含在归档文件中(从文件到文件的所有文件夹)。我只希望文件包含在final.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()
^{} 处理的是字符串而不是列表,因此最好在列表上使用^{} 来筛选实际匹配的字符串:
^{} 不接受字符串列表。你需要^{} 。在
regex用于字符串而不是列表。以下工作
相关问题 更多 >
编程相关推荐