关于python:复制具有特定日期的目录中的文件

Copy Files in directory with specific date

我要复制具有特定日期的文件。我可以过滤掉日期。复制会产生问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os
from os import walk
import time
from datetime import date, timedelta
import zipfile
import io
import shutil

src = 'K:\\Userfiles'
dest = 'L:\\Userfiles'
date1 = date.today() - timedelta(2)

for root, dirs, files in os.walk(src):

  for file in files:
      if ( 'zip' in file):
        x = file[-18:-8]
        d = date1.strftime('%Y-%m-%d')
        if x == d:

            shutil.copyfile(file, dest)

ERROR is: FileNotFoundError: [Errno 2] No such file or directory.

Traceback (most recent call last):
File"C:/Python37/datetime_finder.py", line 28, in shutil.copyfile(file, 'K:\Userfiles\Ucar\UNZIP')
File"C:\Python37\lib\shutil.py", line 120,
in copyfile with open(src, 'rb') as fsrc: FileNotFoundError: [Errno 2] No such file or directory: 'getContents_2019-01-27.csv.zip


采取从https://docs.python.org / 3 /图书馆/ shutil.html # shutil.copyfile

shutil.copyfile(src, dst, *, follow_symlinks=True)

Copy the contents (no metadata) of the file named src to a file named dst and return dst. src and dst are path names given as strings. dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.


因此,你在这shutil.copyfile(file, dest)误差线

提完整的路径应该解决的问题。

前:

1
shutil.copyfile(os.path.join(root, file),".")


如果我不是你弄错了,你的价值被设置在destfor环内,这样shutil.copyfile失败(空字符串)作为''意义不作为第二参数。如果你想为侧音.zip复制只读文件是使用:

1
if file.endswith('zip'):

而不是

1
if ('zip' in file):

所以这是True例如for 'my_list_of_zip_files.txt',所以记住sensitiveness案例,所以它可能是更好的使用下面的if

1
if file.lower().endswith('zip'):