gpt4 book ai didi

python - 无法在 python 中移动文件? Errno 13- 权限被拒绝

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:12 25 4
gpt4 key购买 nike

这是我的代码:

def unpack(folders):
for folder in folders:
files = os.listdir(folder)
print (files)
while len(os.listdir(folder)) != 0:
for file in files:
if os.path.isdir(file)==False:
print (file)
shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
else:
unpack(file)


if len(os.listdir(folder))==0:
os.rmdir(folder)

当我在这个程序所在的目录上调用它时,一切正常,但我无法复制名为“desktop.ini”的文件。这是错误:

Traceback (most recent call last):
File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 544, in move
os.rename(src, real_dst)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\satvi_000\\Downloads\\others\\desktop.ini' -> 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\satvi_000\Downloads\clean_folder.py", line 37, in <module>
unpack(folders_list)
File "C:\Users\satvi_000\Downloads\clean_folder.py", line 30, in unpack
shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 558, in move
copy_function(src, real_dst)
File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 257, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 121, in copyfile
with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'

我猜这是系统文件之类的。我该如何克服这个问题?移动文件并不是完全必要的,跳过它就可以了。

最佳答案

您的错误已包含所有需要的信息:FileExistsError: [WinError 183] 当该文件已存在时无法创建文件:'C:\\Users\\satvi_000\\Downloads\\others\\desktop.ini ' -> 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'

desktop.ini 文件是 Windows 上的隐藏系统文件,包含有关特殊外观或文件夹名称的信息。

我的 Documents 文件夹中的 desktop.ini 文件的示例内容:

[.ShellClassInfo]
LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21770
IconResource=%SystemRoot%\system32\imageres.dll,-112
IconFile=%SystemRoot%\system32\shell32.dll
IconIndex=-235

您可以看到它包含有关本地化名称的信息(在德语 Windows 上它自动显示为 Dokumente)、特殊图标以及有时“虚拟文件夹”的属性。这意味着您应该尝试移动这些文件,因为它们可能会破坏文件夹的正常外观和属性(想想回收站)。

由于一般Windows系统上很多desktop.ini文件,遇到这种问题的情况并不少见。在我的系统上,目前有 166 个这样的文件:

>>> from glob import glob
>>> print(len(glob(r"c:\**\desktop.ini", recursive=True)))
166

我个人建议与 Nuageux 相同 - 只需尝试移动并记录/忽略错误:

try:
shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
except FileExistsError as e:
print("The file {} already exists. Error message: {}".format(os.path.join(cur_dir,file), e))

另一种方法是检查每个文件的名称是否为 desktop.ini

关于python - 无法在 python 中移动文件? Errno 13- 权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44967252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com