Python shutil.move()-目标文件不存在的错误消息
我有以下代码将CSV文件排序到目录结构中,类似于创建CSV文件的WAV文件:Python shutil.move()-目标文件不存在的错误消息,python,python-2.7,shutil,Python,Python 2.7,Shutil,我有以下代码将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 =
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_路径中有包含WAV文件的子文件夹,例如
g:\wav_files\test007\run001\
g:\wav_files\test007\run002\
由于CSV文件位于g:\CSV\u files\test007中,因此我想克隆目录结构并将CSV文件移动到正确的文件夹中。最后,我想让例如:\csv\u files\test007\run001\包含与WAV文件对应的csv,例如:\WAV\u files\test007\run001\
问题是shutil.move命令给了我一个IOError[Errnor 2],抱怨目标不存在。这让我很困惑,因为我有对目标的写访问权,而shutil.move声称目标目录不必存在 我是不是遗漏了什么 打印功能可正确打印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'
信息:我将带有块的错误抛出部分直接添加到我的代码中,它没有抛出错误。现在我自己复制文件,然后删除它们
这似乎是shutil.move如何运行的一个缺陷 我稍微修改了您的代码,我认为它产生了预期的结果
#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之前,我还在此处添加了以下逻辑输入代码
if not os.path.exists(dst):
os.makedirs(dst)
希望它也能为你工作 shutil.move声明目标目录不必存在。。我不是这样读这本书的。它确实说目标目录必须不存在,但我认为如果src是一个目录,而不是当它是一个文件时,目标目录必须存在。我在shutil.move命令之前添加了if not os.path.existsos.path.dirnamedst:os.makedirsos.path.dirnamedst,该命令将在正确的位置创建目录,但是shutil.move仍然无法声明目标不存在。