【问题标题】:shutil.move() - error message that the destination file does not existshutil.move() - 目标文件不存在的错误信息
【发布时间】:2014-11-17 11:53:55
【问题描述】:

我有以下代码将 CSV 文件排序到类似于创建 CSV 文件的 WAV 文件的目录结构中:

from __future__ import print_function

import os
import shutil

WAV_FILES_PATH = 'g:\\wav_files\\test007\\'
CSV_FILES_PATH = 'g:\\csv_files\\test007\\'

wav_files_path = os.walk(WAV_FILES_PATH)
csv_files_path = os.walk(CSV_FILES_PATH)

# I'm only interested in CSV files in the root for CSV_FILES_PATH
(csv_root, _, csv_files) = csv_files_path.next()

print('Running ...')
for root, subs, files in wav_files_path:
    for file_ in files:
        if file_.endswith('wav'):
            for csv_file in csv_files:
                if(file_.split('.')[0] in csv_file):
                    src = os.path.join(csv_root, csv_file)
                    dst = os.path.join(csv_root, root.replace(WAV_FILES_PATH, ''), csv_file)
                    print('Moving "%s" to "%s" ...' % (src, dst))
                    shutil.move(src, dst)

WAV_FILES_PATH 中有包含 WAV 文件的子文件夹,例如

g:\wav_files\test007\run001\
g:\wav_files\test007\run002\

由于 CSV 文件在 g:\csv_files\test007 中的位置无序,我想克隆目录结构并将 CSV 文件移动到正确的文件夹中。最后,我想拥有例如g:\csv_files\test007\run001\ 包含与g:\wav_files\test007\run001\ 中的WAV 文件对应的CSV。

问题是shutil.move() 命令给了我一个IOError [Errnor 2] 抱怨DESTINATION 不存在。这让我很困惑,因为我对目标有写访问权,而 shutil.move() 声称目标目录不必存在。

我错过了什么吗?

print() 函数正确打印出 src 和 dst。

这是错误输出:

[...]
C:\Python27\lib\shutil.pyc in copyfile(src, dst)
     80                 raise SpecialFileError("`%s` is a named pipe" % fn)
     81 
     82     with open(src, 'rb') as fsrc:
---> 83         with open(dst, 'wb') as fdst:
     84             copyfileobj(fsrc, fdst)

IOError: [Errno 2] No such file or directory: 'g:\\csv_files\\test007\\run001\\recording_at_20140920_083721.csv'

INFO:我将错误抛出部分(with 块)直接添加到我的代码中,它没有抛出错误。现在我自己复制文件,然后删除它们。

这似乎是 shutil.move() 运行方式中的一个错误。

【问题讨论】:

  • "shutil.move() 声称目标目录不必存在。"。这不是我阅读documentation 的方式。它确实说“目标目录必须不存在。”,但如果src 是一个目录,而不是一个文件,我会保留它。
  • 我在shutil.move() 命令之前添加了if not os.path.exists(os.path.dirname(dst)): os.makedirs(os.path.dirname(dst)),该命令会在正确的位置创建目录,但shutil.move() 仍然无法声称目标不存在。

标签: python python-2.7 shutil


【解决方案1】:

我稍微修改了您的代码,我认为它会产生预期的结果。

#dst = os.path.join(csv_root, root.replace(WAV_FILES_PATH, ''), csv_file)
dst = os.path.join(csv_root, root.replace(WAV_FILES_PATH, '')) # Modified

在执行shutil.move()之前我还添加了以下逻辑enter code here

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

希望它也对你有用!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多