问题描述
我在python中使用os,openpyxl和win32com.client将工作表从许多文件复制到1。 我的代码: '''
file_list = df['file_names'].unique().tolist()
#create a blank excel file
filepath = (report_path + '\\Combined Files.xlsx')
wb = openpyxl.Workbook()
wb.save(filepath)
# copy sheets in reverse order to new file
for s in (file_list[::-1]):
path1 = report_path + '\\' + s + '.xlsx'
path2 = filepath
xl = Dispatch("Excel.Application")
wb1 = xl.Workbooks.Open(Filename=path1)
wb2 = xl.Workbooks.Open(Filename=path2)
ws1 = wb1.Worksheets(1)
ws1.Copy(Before=wb2.Worksheets(1))
wb2.Close(SaveChanges=True)
xl.Quit()
# remove files
for f in file_list:
path = os.path.join(location,f)
os.remove(path)
print("%s has been removed successfully" %f)
'''
运行代码时出现以下错误
os.remove(path)PermissionError:[WinError 32]该进程无法访问文件,因为该文件正被另一个进程使用:文件名
我已经进行了搜索,但是找不到与我的代码相关的任何答案-或者我可以弄清楚如何使用 Here,Here,Here和Here
任何帮助将不胜感激 谢谢
解决方法
更仔细地研究这一点,看来您的逻辑可能有缺陷。 您应该在读取每个文件并将其添加到输出文件的循环之前打开输出文件(“ wb2 =“行)。所以...
Open the output file for writing
For each input file in the reverse list:
Open the input file
Write its contents to the output file
Close the input file
Delete the input file
Write out/store the final output file
我认为这更符合您的逻辑。
祝您编程愉快!
====旧答案==== 每次循环时,您打开两个文件(wb1和wb2),但仅关闭一个文件(wb2)。尝试同时关闭两者。由于库代码中的错误,可能是未释放的资源。
此外,您的缩进不可用,这使得您难以理解要执行的操作。通常,如果您可以发布运行的代码,这通常会很有帮助,这样就可以重现错误,以便任何人发布答案都可以轻松地验证其发布的准确性。
祝您编程愉快!