我正在使用openpyxl来帮助批量复制Excel中列表中的特定filo。目前正在遵循的流程是: 在工作表中搜索特定的文件名前缀 如果在列表中找到文件名,并以特定前缀开头,则从文件夹中复制:
#Import required modules
from openpyxl import load_workbook
import os
import shutil
# Enter source folder
source = ("C:\\Users\\alec.litchfield\\Desktop\\Resized images\\")
# Enter destiantion folder - this must exist.
destination = ("C:\\Users\\alec.litchfield\\Desktop\\Stripped Blackpool Photos\\")
# Enter the name of your Excel Workbook (including the extension):
workBookName = ("C:\\Users\\alec.litchfield\\Desktop\\2017.11.22 Point Data - Master.xlsx") #input("Enter the name of your Excel Workbook (including the extension): ")
workSheetName = ("Point data") #input("Enter the name of the work sheet to read from: ")
RowRange = int(input ("add total number of rows to check: "))
workBook = load_workbook(filename = workBookName, read_only=True,data_only=True)
workSheet = workBook[workSheetName]
#filepath = ("C:\\Users\\alec.litchfield\\Desktop\\My Personal Folder\\Python lessons\\Photo copy paste\\")
for x in range(2, RowRange):
file = str (workSheet["j" + str(x)].value)
if file.startswith(('P1010','P1020', 'P1070','P1060','P1050' 'P1040' 'P1020' )):
shutil.copyfile (source + file, destination + file)
我得到的问题是,如果文件不存在,则进程停止。这只需要一个导致停止,并且在处理我们正在复制的文件数量时会出现问题(4000)
是否有一个简单的代码添加,以告诉它'文件是否存在,忽略并继续'
非常感谢提前!
艾力
答案 0 :(得分:0)
查看python例外函数(尝试,最后除外)
例如:
try:
#do stuff with the file here
except FileNotFoundError:
#do nothing if the file is not found
pass