如何将文件复制到文件夹名称每天更改的文件夹

时间:2019-07-08 15:57:45

标签: python

因此,我在“ source_path”处有一些文件。我正在尝试将它们复制到“ dest_path”和“ dest_path2”。 “ Dest_path2”每天都会更改,因为完整的文件夹名称包含变量“ today2”,这只是以特定方式格式化的今天的日期。

我可以将文件复制到“ Dest_path”,而不会出现问题,但是“ dest_path2”在复制文件时会挂起。它正在正确格式化文件夹名称,但似乎认为文件不存在(它们在那里)。


import os
import shutil
from shutil import copyfile
import time
import datetime

today = datetime.date.today()
today2 = today.strftime("%d-%b-%Y")
os.mkdir("c:\\users\\<user>\\desktop\\TEST" + "-" + today2)

#establish paths
source_path = "C:\\Users\\<user>\\Desktop\\Downloaded\\"
dest_path = "C:\\Users\\<user>\\Desktop\\" 
dest_path2 = "C:\\Users\\<user>\\Desktop\\TEST - %s\\" %(today2)

#move files
for reports in os.listdir(source_path):
    if reports.startswith("EiS"):
        shutil.copyfile(source_path + reports, dest_path + reports)
        print(dest_path2)
        shutil.copyfile(source_path + reports, dest_path2 + reports)
        print(reports)

错误:

Traceback (most recent call last):
  File "C:\Users\<user>\Desktop\copy_remote_3.py", line 22, in <module>
    shutil.copyfile(source_path + reports, dest_path2 + reports)
  File "C:\Python27\lib\shutil.py", line 97, in copyfile
    with open(dst, 'wb') as fdst:
IOError: [Errno 2] No such file or directory: 'C:\\Users\\<user>\\Desktop\\TEST - 08-Jul-2019\\<name of first file in source_path>'

1 个答案:

答案 0 :(得分:0)

似乎您已命名创建的文件夹和目标路径略有不同。差异是不可察觉的,但在字符串串联中会发生。最好的选择是为目标路径创建变量,然后在mkdirshutil操作中都使用它。

import os
import shutil
from shutil import copyfile
import time
import datetime

today = datetime.date.today()
today2 = today.strftime("%d-%b-%Y")

#establish paths
source_path = "C:\\Users\\<user>\\Desktop\\Downloaded\\"
dest_path = "C:\\Users\\<user>\\Desktop\\" 
dest_path2 = "C:\\Users\\<user>\\Desktop\\TEST - %s\\" %(today2)

#apart from re-ordering this is the main change in the code.
os.mkdir(dest_path2)


#move files
for reports in os.listdir(source_path):
    if reports.startswith("EiS"):
        shutil.copyfile(source_path + reports, dest_path + reports)
        print(dest_path2)
        shutil.copyfile(source_path + reports, dest_path2 + reports)
        print(reports)

我进行了此更改,并在一些测试用例上进行了工作。