【问题标题】:Copy Files Using Python使用 Python 复制文件
【发布时间】:2017-08-29 21:23:58
【问题描述】:

我正在尝试将文件从当前目录复制到当前目录中新创建的文件夹。文件夹名称是脚本使用时间模块运行的确切日期和时间。我正在尝试使用 shutil 模块,因为每个人似乎都说这是将文件从一个地方复制到另一个地方的最佳方法,但我不断收到权限错误。我已经粘贴了代码和下面的错误。有什么建议么?提前致谢。

import os
import time
from shutil import copyfile

oldir = os.getcwd()
print(oldir)
timestr = time.strftime("%Y%m%d-%H%M%S")
print('timestr: {}'.format(timestr))
newdir = os.path.join(oldir + "\\" + timestr)
print(newdir)


for filename in os.listdir(os.getcwd()):
    if filename.startswith("green"):
        print (filename)
        copyfile(oldir, newdir)

错误:

Traceback (most recent call last):
  File "\\directory\directory\Testing1.py", line 16, in <module>
    copyfile(oldir, newdir)
  File "C:\Python36-32\lib\shutil.py", line 120, in copyfile
    with open(src, 'rb') as fsrc:
PermissionError: [Errno 13] Permission denied: '\\\\directory\\directory'

【问题讨论】:

  • 这是因为您尝试将当前目录本身复制到其子目录中,而不是复制文件。

标签: python filesystems shutil


【解决方案1】:

您需要先创建目录,然后在制作副本时,使用起始文件和结束文件的完整路径

import os
import time
from shutil import copyfile

oldir = os.getcwd()
print(oldir)
timestr = time.strftime("%Y%m%d-%H%M%S")
print('timestr: {}'.format(timestr))
newdir = os.path.join(oldir + "\\" + timestr)
print(newdir)

if not os.path.exists(newdir):
    os.makedirs(newdir)

for filename in os.listdir(os.getcwd()):
    if filename.startswith("green"):
        print (filename)
        copyfile(oldir+"\\"+filename, newdir + "\\" + filename)

【讨论】:

  • 正如所指出的,如果不检查目录是否存在或您先创建它,则无法复制@Matt
猜你喜欢
  • 2012-12-05
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
  • 2019-07-20
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多