将文件移动到多个目的地

问题描述 投票:-4回答:1

我试图将路径文件夹中的文件移动到多个目标目录。所以我的条件是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'
python readfile writefile
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.