|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
需求:现在【1】文件夹下有无数个文件,现在想把他们以150个为一组,放到【2】文件夹下。现在每次运行都出错,请大佬指点
update:现在已知是‘str(num)’的问题,不好解决。
代码如下
import os
import shutil
n=0
m=1
allfiles=[]
path=r'e:\1'
path2=r'e:\2'
def mkdir(name):
os.chdir(path2)
if not os.path.exists(name):
os.mkdir(name)
for root,dirs,files in os.walk(path):
for file in files:
allfiles.append(os.path.join(root,file))
n+=1
num=range(len(allfiles))
for num,file in zip(num,allfiles):
if num%150==0:
mkdir(str(num))
print(num,file)
shutil.move(file,os.path.join(path2,str(num),os.path.basename(file)))
出错的信息如下:
0 e:\1\0\9015.gif
Traceback (most recent call last):
File "D:\Python39\lib\shutil.py", line 815, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'e:\\1\\0\\9016.gif' -> 'e:\\2\\1\\9016.gif'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:\Python_PC\删除.py", line 24, in <module>
shutil.move(file,os.path.join(path2,str(num),os.path.basename(file)))
File "D:\Python39\lib\shutil.py", line 835, in move
copy_function(src, real_dst)
File "D:\Python39\lib\shutil.py", line 444, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "D:\Python39\lib\shutil.py", line 266, in copyfile
with open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: 'e:\\2\\1\\9016.gif'
本帖最后由 hrpzcf 于 2022-8-8 16:51 编辑
因为num是随着每个文件一直增加的,而你最后一句使用num合成目的地路径,遍历到第二个文件的时候num是1,而这时候文件夹1并没有创建(你是每隔150个文件创建一个文件夹),所以报错了。 import os
import shutil
n = 0
m = 1
allfiles = []
path = r"e:\1"
path2 = r"e:\2"
def mkdir(name):
os.chdir(path2)
if not os.path.exists(name):
os.mkdir(name)
for root, dirs, files in os.walk(path):
for file in files:
allfiles.append(os.path.join(root, file))
n += 1
dirindex = -1
num = range(len(allfiles))
for num, file in zip(num, allfiles):
if num % 150 == 0:
dirindex += 1
mkdir(str(dirindex))
print(num, file)
shutil.move(file, os.path.join(path2, str(dirindex), os.path.basename(file)))
|
|