簡體   English   中英

PermissionError: [WinError 5] 運行腳本時

[英]PermissionError: [WinError 5] when running script

我收到了代碼片段底部注釋掉的錯誤。 我在 IDLE 中運行所有這些。 我在 windows 上,並嘗試在 IDLE 上以管理員身份右鍵單擊運行,認為這可能會有所幫助,但它不起作用。 我以前運行過這樣的代碼來完成相同的任務,但在不同的文件夾上。 我也知道還有其他更簡單的方法來移動文件,但由於我正在按照書中的練習進行操作,我想以盡可能接近的方式完成將多個文件移動到不同目錄的最終目標我在下面描述的。 具體來說,我正在尋找有關導致此錯誤的原因並了解原因的輸入。

我看到了這個視頻,從 [7:40] 開始。 上下文有點不同,但錯誤消息是一樣的。 即便如此,我看不出解釋與我正在做的事情有何關系,特別是在我的 python 上下文中。 任何幫助將非常感激!

import pathlib
import shutil

home = pathlib.Path.home()
pictures = home / "Pictures"
imgfiles = pictures / "imgfiles"
file1 = pictures / "image1.png"
file2 = pictures / "image2.gif"
file3 = pictures / "Uplay" / "image3.png"
file4 = pictures / "camera roll" / "image4.jpg"
filelist = [file1, file2, file3, file4]
sourcefiles = []
destination = imgfiles

for file in filelist:
    file.touch()

for file in pictures.rglob("image?.???"):
    sourcefiles.append(file)

for path in sourcefiles:
    path.replace(destination)

回溯如下所示:

Obtain the following Error when running the last line of code: PermissionError: [WinError 5]
Traceback (most recent call last):
 File "<pyshell#42>", line 2, in <module>
   path.replace(destination)
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38\lib\pathlib.py", line 1366, in replace
   self._accessor.replace(self, target)
PermissionError: [WinError 5] Acesso negado: 'C:\\Users\\XXXX\\Pictures\\image1.png' -> 'C:\\Users\\XXXX\\Pictures\\imgfiles'

您正在嘗試將文件寫入目錄,而 Windows 不喜歡這樣。 如果你用目標文件名替換你的目標,它會工作得很好。

所以如果我要重寫你的代碼,我會這樣做: -

import pathlib
import shutil

home = pathlib.Path.home()
pictures = home / "Pictures"
imgfiles = pictures / "imgfiles"
file1 = pictures / "image1.png"
file2 = pictures / "image2.gif"
file3 = pictures / "Uplay" / "image3.png"
file4 = pictures / "camera roll" / "image4.jpg"
filelist = [file1, file2, file3, file4]
sourcefiles = []
destination = imgfiles

for file in filelist:
    file.touch()

for file in pictures.rglob("image?.???"):
    destination=imgfiles/ str(file)[str(file).rfind("\\")+1:]  #Added
    file.replace(destination)

#Commented
#for path in sourcefiles: 
#    path.replace(destination) 

希望有幫助。

代替:

for path in sourcefiles:
    path.replace(destination)

和:

for path in sourcefiles:
    path.replace(destination / path.name)

來自 RealPython 的 Bart 非常感謝他的回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM