![](/img/trans.png)
[英]Writing to file and running the files sometimes works, mostly only first one
[英]Matching files based on file name, then copying the found file but it only works if there is only one file in the first folder
这与我的另一篇文章有关,但我认为这会提出一个更具体的问题。
我需要根据文件名中出现的员工姓名匹配文件。 如果我设法说服我的同事他们遵守命名约定,我想我可以编写一些代码来自动复制。 .pdf 文件都是扫描件。
我找到了解决我的问题的部分解决方案,但是我编写的代码仅在代码查看的第一个文件夹中只有一个文件时才有效。 员工姓名具有特殊字符:
č ć š ž đ
例如原始文件夹中的文件:
Džafer Kapetanović - napotitev 13。 宜家,Einrichtungshaus Graz.pdf
Nedim Muratović - napotitev 13。 阿尔迪,福拉尔贝格州.pdf
以及我需要匹配和复制的文件(A1 文件夹):
Džafer Kapetanović - A1 13。 09.09.2020 - 07.08.2021.pdf
Nedim Muratović - A1 13。 01.01.2020 - 01.01.2021.pdf
代码如下:
import os
import shutil
import pathlib
import pprint
import filecmp
from os.path import join
import re
dir = (#Path to the folder where the originals are dumped)
#added A1_dir to have it stored for later.
A1_dir = (#Path to the A1 folder)
#get the list of files
files = os.listdir(dir)
A1_files = os.listdir(A1_dir)
#generate first name list
name_list = []
for filename in A1_files:
if '-' in filename:
file_name = filename.split('-')[0]
else:
file_name = filename.split('.') [0]
if file_name not in name_list:
name_list.append(file_name)
#generate second name list
name_list_2 = []
for filename in files:
if '-' in filename:
file_name = filename.split('-')[0]
else:
file_name = filename.split('.') [0]
if file_name not in name_list_2:
name_list_2.append(file_name)
#make a list of the names that match
matched_names = [x for x in name_list if x in name_list_2]
#print here for now to see if it works
print(matched_names)
#copy files that have a matching name in their filenames. Currently only works with 1 file in the folder.
for filename in A1_files:
full_a1_filename = os.path.join(A1_dir, filename)
if (all(name in filename for name in matched_names)):
print("Match found:", filename)
shutil.copy(full_a1_filename, dir)
我认为您应该在最后一个 for 循环中使用any
而不是all
? 但也许我不理解这个问题。
for filename in A1_files:
full_a1_filename = os.path.join(A1_dir, filename)
if (any(name in filename for name in matched_names)):
print("Match found:", filename)
shutil.copy(full_a1_filename, dir)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.