我正在尝试将路径文件夹中的文件移动到多个目标目录。所以我的条件是将文件的70%移至dest1,将30%的文件移至dest2。到目前为止,我尝试过的工作给了我一些错误。我不确定逻辑是否错误或如何执行此操作。请发布您的解决方案或想法。 谢谢
代码:
import os
import shutil
import random
from shutil import copyfile
path="/Users/kj/Downloads/spam_classifier-master2/data2/data"
dest1="/Users/kj/Downloads/test"
dest2="/Users/kj/Downloads/train"
files=os.listdir(path)
for f in files:
if (len(f) >0.7 ):
shutil.move(f,dest2)
elif (len(f)<0.3):
shutil.move(f,dest1)
错误:
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 544, in move
os.rename(src, real_dst)
FileNotFoundError: [Errno 2] No such file or directory: 'mail0.txt' -> '/Users/kj/Downloads/train'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/kj/Downloads/ef.py", line 13, in <module>
shutil.move(f,dest2)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 558, in move
copy_function(src, real_dst)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 257, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'mail0.txt'
答案 0 :(得分:0)
os.listdir
仅返回给定路径下的文件名,因此对文件名执行操作时,应将文件名与路径连接起来,以首先获取完整路径。另外,您应该将文件编号除以文件列表的长度,以获得适当的比率:
files=os.listdir(path)
for i, f in enumerate(files):
if (i + 1) / len(files) > 0.7:
shutil.move(os.path.join(path, f),dest2)
else:
shutil.move(os.path.join(path, f),dest1)