【问题标题】:Copy Files in directory with specific date复制具有特定日期的目录中的文件
【发布时间】:2019-01-29 12:06:06
【问题描述】:

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

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)

错误是: FileNotFoundError: [Errno 2] 没有这样的文件或目录。

回溯(最近一次通话最后一次):
文件“C:/Python37/datetime_finder.py”,第 28 行,在 shutil.copyfile(file, 'K:\Userfiles\Ucar\UNZIP')
文件“C:\Python37\lib\shutil.py”,第 120 行,
在副本文件中,打开(src,'rb')为 fsrc:FileNotFoundError:[Errno 2] 没有这样的文件或目录:'getContents_2019-01 -27.csv.zip

【问题讨论】:

  • 错误是:FileNotFoundError:[Errno 2] 没有这样的文件或目录:
  • 你能发布完整的错误跟踪吗?看起来dest 是一个空字符串。如果您需要复制到当前工作目录,您应该使用dest = '.' 明确提及
  • Traceback(最近一次调用最后):文件“C:/Python37/datetime_finder.py”,第 28 行,在 shutil.copyfile(file, 'K:\\Userfiles\\Ucar \\UNZIP')文件“C:\Python37\lib\shutil.py”,第 120 行,在副本文件中,open(src, 'rb') as fsrc: FileNotFoundError: [Errno 2] No such file or directory: 'getContents_2019 -01-27.csv.zip' >>>
  • 当我运行 print(file) 时,它会显示所有带有日期的文件。我想复制这个。

标签: python python-3.7


【解决方案1】:

取自https://docs.python.org/3/library/shutil.html#shutil.copyfile

shutil.<b>copyfile</b>(<i>src</i>, <i>dst</i>, <i>*</i>, <i>follow_symlinks=True</i>)

将名为src的文件的内容(无元数据)复制到名为dst的文件并返回dst . srcdst 是以字符串形式给出的路径名。 dst 必须是完整的目标文件名;查看shutil.copy() 以获取接受目标目录路径的副本。

【讨论】:

  • if语句后如何复制?
  • 您所要做的基本上就是指定完整的目标文件名,以便您的脚本工作。你不能留下一个空的目的地,否则它会抛出你当前遇到的错误。
【解决方案2】:

如果我没记错的话,您在内部for 循环中缺少设置dest 值,因此shutil.copyfile 失败,因为''(空字符串)作为第二个参数没有意义。作为旁注,如果您只想复制 .zip 文件,最好使用:

if file.endswith('zip'):

而不是

if ('zip' in file):

这也是True,例如'my_list_of_zip_files.txt',也要注意区分大小写,所以最好使用if

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

【讨论】:

    【解决方案3】:

    您在此行中收到错误shutil.copyfile(file, dest)

    提及完整路径应该可以解决问题。

    例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多