0
votes

I want to copy files that have specific date. I can filter out the date. Copying makes problems.

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

3
ERROR is: FileNotFoundError: [Errno 2] No such file or directory: - mgm841
can you post the full error trace? looks that dest is an empty string. if you need to copy to current working directory you should mention it explicitly using dest = '.' - Swadhikar
Traceback (most recent call last): File "C:/Python37/datetime_finder.py", line 28, in <module> 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' >>> - mgm841
When I run print(file), its shows me all files with the date. I would like to copy this. - mgm841

3 Answers

1
votes

Taken from https://docs.python.org/3/library/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.

0
votes

If I am not mistaken, you are missing setting dest value inside your inner for loop, so shutil.copyfile fails as '' (empty string) does not make sense as second argument. As side note if you want to copy only .zip files it is better to use:

if file.endswith('zip'):

instead of

if ('zip' in file):

which is also True for example for 'my_list_of_zip_files.txt', also keep in mind case-sensitiveness, so it might be better to use following if

if file.lower().endswith('zip'):
0
votes

You are getting the error in this line shutil.copyfile(file, dest)

Mentioning the full path should fix the problem.

Ex:

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