如果文件不存在,如何省略openpyxl,os

2024-09-25 10:30:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用openpyxl帮助从Excel中的列表批量复制特定的文件。目前所遵循的流程是: 在工作表中搜索特定的文件名前缀 如果在列表中找到文件名,并以特定前缀开头,请从文件夹复制:

#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)

我得到的问题是,如果文件不存在,那么进程就会停止。这只需要一个就可以导致停止,并且在处理要复制的文件的numebr时会出现问题(4000)

是否有一个简单的代码添加,以告诉它“如果文件不存在,忽略并继续”

先谢谢你!在

亚历克


Tags: 文件ofthenameimportsourceinputexcel
1条回答
网友
1楼 · 发布于 2024-09-25 10:30:41

查看python异常函数(try,except,finally)

例如:

try:
    #do stuff with the file here
except FileNotFoundError:
    #do nothing if the file is not found
    pass

相关问题 更多 >