要求:使用Python 进行这样的操作: 1. 把 jpg,png,gif 文件夹中的所有文件移动到 image 文件夹中,然后删除 jpg,png,gif 文件夹
2. 把 doc,docx,md,ppt 文件夹中的所有文件移动到 document 文件夹中,然后删除
自己写的代码:
import os
import shutil
path = '/Users/huangxuan/Downloads/problem2_files'
files = os.listdir(path)
folder_name_1 = path + '/images'
folder_name_2 = path + '/documents'
if not os.path.exists(folder_name_1):
os.makedirs(folder_name_1)
elif not os.path.exists(folder_name_2):
os.makedirs(folder_name_2)
for i in files[1:]:
files_docu = os.listdir(path + '/' + i)
print(files_docu)
for j in files_docu:
if j.endswith('.jpg') or j.endswith('.png') or j.endswith('.gif'):
shutil.move(path + '/' + i + '/' + j,folder_name_1)
else:
shutil.move(path + '/' + i + '/' + j,folder_name_2)
os.removedirs(path + '/' + i +'/'+j)
运行不成功,显示NotADirectoryError: [Errno 20] Not a directory: '/Users/huangxuan/Downloads/problem2_files/jpg/world5.jpg错误或者显示某文件在文件夹中已经存在错误。想知道思路错在哪里。感谢大佬留言~
课程给的参考答案:import os
import shutil
# 需要把路径替换成你的文件夹所在路径,当把这个代码文件放在要处理的文件夹外一层时,可以使用下面的相对路径写法
path = '/Users/huangxuan/Downloads/problem2_files'
# 创建目标文件夹
os.makedirs(path + '/image')
os.makedirs(path + '/document')
# 将需要处理的后缀名存储到list中
image_suffix = ['jpg', 'png', 'gif']
doc_suffix = ['doc', 'docx', 'ppt', 'md']
# 移动jpg、png、gif文件中的文件
for i in image_suffix:
cur_path = path + '/' + i
files = os.listdir(cur_path)
for f in files:
# 移动文件夹中的文件
shutil.move(cur_path + '/' + f, path + '/image')
# 删除文件夹
os.removedirs(cur_path)
# 移动doc、docx、md、ppt文件夹中的文件,步骤与前面类似
for d in doc_suffix:
cur_path = path + '/' + d
files = os.listdir(cur_path)
for f in files:
shutil.move(cur_path + '/' + f, path + '/document')
os.removedirs(cur_path)
|