我是 Python 的新手。我一直在探索shutil
模块,可以移动一般事物。我的问题围绕着:
想象一下,在导出文件夹中有数百个文件的场景。虽然所有文件都是不同的,但每个文件中有13个是针对特定供应商的。我想创建一个遍历导出文件夹的脚本,评估每个文件名,抓取所有Apple文件并将它们放入Apple文件夹,Intel文件并将它们放入英特尔文件夹等。任何智慧都将非常感激
我试图在shutil
副本中使用通配符,但没有任何运气。
谢谢,
JT
答案 0 :(得分:15)
我能想到的最简单的解决方案:
import shutil
import os
source = '/path/to/source_folder'
dest1 = '/path/to/apple_folder'
dest2 = '/path/to/intel_folder'
files = os.listdir(source)
for f in files:
if (f.startswith("Apple") or f.startswith("apple")):
shutil.move(f, dest1)
elif (f.startswith("Intel") or f.startswith("intel")):
shutil.move(f, dest2)
目标文件夹执行需要存在。
答案 1 :(得分:2)
import glob, shutil
for file in glob.glob('path_to_dir/apple*'):
shutil.move(file, new_dst)
# a list of file types
vendors =['path_to_dir/apple*', 'path_to_dir/intel*']
for file in vendors:
for f in (glob.glob(file)):
if "apple" in f: # if apple in name, move to new apple dir
shutil.move(f, new_apple_dir)
else:
shutil.move(f, new_intel_dir) # else move to intel dir
答案 2 :(得分:1)
假设文件名中有特定的字符串来标识报告与哪个供应商相关,您可以创建一个字典,将这些标识字符串映射到适当的供应商。例如:
import shutil
import os
path = '/path/to/location'
vendorMap = {'apple': 'Apple',
'intel': 'Intel',
'stringID3': 'vendor3'}
files = os.listdir(path)
for f in files:
for key, value in vendorMap.iteritems():
if key in f.lower():
shutil.copy(f, path + '/' + value)
else:
print 'Error identifying vendor for', f
这将在当前目录中创建一个文件夹,以相应的供应商命名,并在那里复制该供应商的报告。请注意,此示例使用s.lower()方法,因此供应商名称是否大写无关紧要。
答案 3 :(得分:1)
Padaic答案的小编辑:
import glob
import shutil
vendors = ("*Apple*.*", "*Intel*.*")
paths = (".\\Apple\\", ".\\Intel\\")
for idx in range(len(vendors)):
for matches in glob.glob(vendors[idx]):
shutil.move(matches, paths[idx])
答案 4 :(得分:0)
下面的代码对我有用-
import os
import shutil
ent_dir_path = input("Enter the path of the directory:") #source directory
out_dir_path = input("Enter the path of the directory where you want to move all these files:") #destination directory
if not os.path.exists(out_dir_path): #create folder if doesn't exist
os.makedirs(out_dir_path)
file_type = input("Enter the first few characters of type of file you want to move:")
entries = os.listdir(ent_dir_path)
for entry in entries:
if entry.startswith(file_type):
#print(ent_dir_path + entry)
shutil.move(ent_dir_path + entry, out_dir_path)
# ent_dir_path + entry is the path of the file you want to move
# example- entry = Apple.txt
# ent_dir_path = /home/user/Downloads/
# ent_dir_path + entry = /home/user/Downloads/Apple.txt (path of the
# file)