我有以下代码将 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]
抱怨目的地不存在。这让我很困惑,因为我对目标有写入权限,而 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'
信息: 我将错误抛出部分(
with
块)直接添加到我的代码中,它没有抛出错误。现在我自己复制文件然后删除它们。
这似乎是 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)
希望它也对你有用!!!