无法将文件从输入文件夹移动到错误文件夹



我正在尝试运行读取文件表的代码。我面临的问题是,如果有一个文件没有名为SheetSum的工作表,我无法将其移动到错误位置。

示例

def read_file(data_file):
# data_file = 'rrex.xlsx'
sheets = {}
try:
print("Reading file: "+data_file)
sheets['df_1'] = pd.read_excel(open(data_file,'rb'), 'SheetSum')
except Exception as excpt:
print("Exception occurred", exc_info=True)
return sheets
read_file(file)
shutil.move( file, dirpath +'\processed_files')

收到错误为:

[WinError 32] The process cannot access the file because it is being used by another process

更新:

如果存在finally,则指定清理处理程序。Thetry执行条款,包括任何exceptelse条款。如果 异常发生在任何子句中并且未处理,暂时保存异常。执行finally子句。如果 有一个保存的异常,它会在finally结束时重新引发 第。如果finally子句引发另一个异常,则保存的 异常设置为新异常的上下文。

..更多在这里

接受的解决方案就像魅力一样。

尝试在尝试移动文件之前关闭文件。 所以像

def read_file(data_file):
# data_file = 'rrex.xlsx'
sheets = {}
try:
print("Reading file: "+data_file)
sheets_file = open(data_file,'rb')
sheets['df_1'] = pd.read_excel(sheets_file, 'SheetSum')
except Exception as excpt:
print("Exception occurred", exc_info=True)
finally:
sheets_file.close()
return sheets
read_file(file)
shutil.move( file, dirpath +'\processed_files')

问题是文件打开,交给 pandas 方法,当发生异常时,您的文件永远不会关闭。

finally添加到"尝试除外"块可确保文件始终关闭。

相关内容

最新更新