Я написал небольшой скрипт в Spyder, чтобы мы с коллегами могли использовать его для обновления простого файла Excel. Когда я запускаю код, я не получаю ошибок, но когда мой коллега запускает тот же код, мы получаем сообщение об ошибке, заключающееся в том, что процесс не может получить доступ к файлу, поскольку он используется другим процессом.
Я Я попробовал закрыть мою программу, пока они запускают свою, сохранить документы с новыми именами и запустить снова, но ошибка не изменилась.
Вот как файлы выглядят в моей программе. Я удалил здесь начало строки каталога, поскольку она содержит информацию о компании.
#Files
swx_f = Internal Team Library\\Team\\CS\\Darian\\CARISCSPSWX_Report\\SWX' + dayval + '.xlsx'
caris_f = Internal Team Library\\Team\\CS\\Darian\\CARISCSPSWX_Report\\CARIS' + dayval + '.xlsx'
cspcaris_f = Internal Team Library\\Team\\CS\\Darian\\CARISCSPSWX_Report\\CSPvsCARIS' + dayval + '.xlsx'
Код ошибки:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\\\Users\\\\saed\\OneDrive\\Internal Team Library\\Team\\CS\\Darian\\CARISCSPSWX_Report\\SWX202408.xlsx' -> 'C:\\Users\\\\saed\\\\Internal Team Library\\Team\\CS\\Darian\\CARISCSPSWX_Report\\File Archive\\SWX202408.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ~\AppData\Local\anaconda3\Lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
exec(code, globals, locals)
File c:\users\saed\.spyder-py3\monthly closure.py:107
shutil.move(swx_f, dest_new)
File ~\AppData\Local\anaconda3\Lib\shutil.py:868 in move
os.unlink(src)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\\\Users\\\\saed\\ \\Internal Team Library\\Team\\CS\\Darian\\CARISCSPSWX_Report\\SWX202408.xlsx'
Код:
###Headers
length = 0
header1 = ['AWB Number']
header2 = ['Departure Date', 'Match Status', 'Flight Number', 'Net Revenue Prorated', 'Source']
swxhead = ['AWB Number', 'Origin', 'Destination', 'SWX Net Amount']
###Lists/Dicts
swx_list = []
caris_dict = {}
cspcaris_dict = {}
final_dict = {}
###Record Counts
swxcount = 0
cariscount = 0
cspcariscount = 0
#combinedcount = 0
###Build SWX List
workbook1 = xl.load_workbook(filename=swx_f)
wb1 = workbook1.active
for line in wb1.iter_rows(values_only=True):
if line[2] is not None:
if '724-' in line[2]:
swxamt = float(line[10])
amtround = np.around(swxamt, decimals=2)
swx_list.append([line[2].strip(), line[4].strip(), line[5].strip(), amtround])
swxcount +=1
else:
pass
else:
pass
workbook1.close()
shutil.move(swx_f, dest_new)
###Build CARIS List
workbook2 = xl.load_workbook(filename=caris_f)
wb2 = workbook2.active
for row in wb2.iter_rows(values_only=True):
if row[3] is not None:
if '724-' in row[3].strip():
awb = row[3].strip()
depdate = row[4]
flt = row[5]
netrev = row[6]
if awb in caris_dict.keys():
caris_dict[awb] += [depdate, flt, netrev, 'CARIS']
cariscount +=1
else:
caris_dict[awb] = [depdate, flt, netrev, 'CARIS']
cariscount +=1
else:
pass
else:
pass
workbook2.close()
shutil.move(caris_f, dest_new)
###Build CSP vs CARIS List
workbook3 = xl.load_workbook(filename=cspcaris_f)
wb3 = workbook3.active
for r in wb3.iter_rows(values_only=True):
if r[1] is not None:
if '724' in str(r[1]):
awb2 = str(r[1])
depdate2 = r[4].strftime('%d/%m/%Y')
flt2 = r[3]
netrev2 = r[6]
if awb2 in cspcaris_dict.keys():
cspcaris_dict[awb2] += [depdate2, flt2, netrev2, 'CSPCARIS']
cspcariscount +=1
else:
cspcaris_dict[awb2] = [depdate2, flt2, netrev2, 'CSPCARIS']
cspcariscount +=1
else:
pass
else:
pass
workbook3.close()
shutil.move(cspcaris_f, dest_new)
###Build Combined CARIS and CSP vs CARIS Dict
for k in caris_dict.keys():
if k in cspcaris_dict.keys():
final_dict[k] = ['Matched'] + caris_dict[k] + cspcaris_dict[k]
cspcaris_dict[k] += ['Matched']
else:
final_dict[k] = ['No Match'] + caris_dict[k]
for j in cspcaris_dict.keys():
if cspcaris_dict[j][-1] == 'Matched':
pass
elif j in caris_dict.keys():
final_dict[j] = ['Matched'] + caris_dict[j] + cspcaris_dict[j]
else:
final_dict[j] = ['No Match'] + cspcaris_dict[j]
for l in final_dict.keys():
if len(final_dict[l]) > length:
length = len(final_dict[l])
else:
pass
###Write Final File###
###Create report counts for error checking
indtotal = swxcount + cariscount + cspcariscount
####Headers
multiplier = int(length / 5)
variablehead = header2 * multiplier
final_head = header1 + variablehead
###Create workbook and name sheets
wb = xl.Workbook()
ws1 = wb.create_sheet('CARIS CSP', 0)
ws2 = wb.create_sheet('SWX', 1)
ws3 = wb.create_sheet('Record Counts', 2)
ws3.append(['Record Counts - Individual Reports', 'SWX Records:', swxcount, 'CARIS Records:', cariscount, 'CSP vs CARIS Records:', cspcariscount, 'Total:', indtotal])
#ws2.append(['Record Counts - This Report', '', '', 'Combined Records:', combinedcount, 'Unique Records:', uniquecount, 'Total:', reporttotal])
ws2.append(swxhead)
for t in swx_list:
ws2.append(t)
ws1.append(final_head)
for w in final_dict.keys():
newlist = [w] + final_dict[w]
ws1.append(newlist)
outputfile = r'C:\\Users\\' + user_code + '\\\\Internal Team Library\\Team\\CS\\Darian\\CARISCSPSWX_Report\\Completed Reports\\SWXCARISCSP Records Report ' + dayval + 'TESTTEST.xlsx'
wb.save(outputfile)
wb.close()
messagebox.showinfo("Success!", "Report Completed")
master_with_quotes = '"' + outputfile + '"'
os.system('start "EXCEL.exe" {}'.format(master_with_quotes))
Подробнее здесь: https://stackoverflow.com/questions/791 ... by-another
Python — процесс не может получить доступ к файлу, поскольку он используется другим процессом, когда кто-то другой запус ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Процесс не может получить доступ к файлу, поскольку он используется другим процессом.
Anonymous » » в форуме C# - 0 Ответы
- 17 Просмотры
-
Последнее сообщение Anonymous
-