shutil.move 对图像文件的权限被拒绝

Permission denied on shutil.move on image files

我正在尝试移动一些文件。我可以移动除 .png、.jpg 或 .gif 之外的任何扩展类型。当我尝试移动这些类型的文件时,即使我是管理员,我也会得到 "IOError: [Errno 13] Permission denied"。下面的代码

import os, glob, shutil
dir = r'C:\Users\jcan4\Desktop\testmove\*'
print(dir)
files = glob.glob(dir)
files.sort(key=os.path.getmtime)


for i, file in enumerate(files, start=1):
    print(file)
    oldext = os.path.splitext(file)[1]
    shutil.move(file,  'Attachment-%s' % (i) + oldext)

首先要做的事情,你正在双重转义你的 dir 变量:

print(r'C:\Users\jcan4\Desktop\testmove\*')
# Yields 'C:\\Users\\jcan4\\Desktop\\testmove\\*' !!

# What you really meant was either one of the following:
dir_harderToRead = 'C:\Users\jcan4\Desktop\testmove\*'
dir_easyToRead = r'C:\Users\jcan4\Desktop\testmove\*'

如果您仍然遇到错误,那是因为您没有授予 python 脚本 移动文件。有几种方法可以解决这个问题:

Windows

(这适用于提出的问题)

  1. 使用管理权限打开命令提示符(我看到了你的文件路径,我假设你在 windows 上)。 (see here)

  2. 将图像的所有权更改为您。 (参见 here for windows 10 or here for windows 7

Linux (MacOS)

(这适用于 Linux 上可能有同样问题的人)

  1. 运行 具有 root 权限的 python 脚本:
# At command line
sudo python your_script_name.py
  1. 将文件所有权更改为您自己:
# At command line
# Changes ownership of entire directory (CAREFUL):
chmod 755 /absolute/path/to/dir
chmod 755 relative/path/to/dir

# Or you can change file by file:
chmod 755 /absolute/path/to/file
chmod 755 relative/path/to/file

有关详细信息,我在权限上使用了 this site。 (如果有人对 chmod 的数值大于 755,请说明。)