Python根据文件名中的字符移动多个文件到另一个文件夹
我刚接触Python,正在研究shutil
这个模块,基本上可以移动文件了。我的问题是这样的:
想象一下,你有一个导出文件夹,里面有几百个文件。虽然这些文件各不相同,但其中有13个文件是特定供应商的。我想写一个脚本,遍历这个导出文件夹,检查每个文件的名字,把所有苹果公司的文件放到苹果文件夹里,把英特尔的文件放到英特尔文件夹里,依此类推。如果你有什么建议,我会非常感激。
我试着在shutil
的复制中使用通配符,但没有成功。
谢谢,
JT
6 个回答
下面的代码对我来说是有效的 -
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)
对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])
假设文件名中有一些特定的字符串,可以用来识别报告属于哪个供应商,你可以创建一个字典,把这些识别字符串和相应的供应商对应起来。例如:
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() 方法,这样不管供应商的名字是大写还是小写都没关系。
在编程的世界里,很多时候我们会遇到一些问题或者错误。这些问题可能是因为代码写得不够好,或者是因为我们没有理解某些概念。比如,有时候我们在运行程序时,可能会看到一些错误信息,这些信息就像是程序在告诉我们:“嘿,我遇到麻烦了!”
解决这些问题的第一步就是要仔细阅读错误信息,理解它的意思。很多时候,错误信息会告诉我们出错的地方,甚至会给出一些建议,帮助我们找到解决办法。
另外,编程中有很多常见的错误,比如拼写错误、缺少符号、或者是使用了不正确的变量名。这些错误听起来简单,但在代码中却可能导致程序无法正常运行。
所以,作为一个编程小白,最重要的是要耐心,遇到问题时不要着急。可以尝试查找相关的资料,或者向其他人请教。记住,编程是一个不断学习和实践的过程,慢慢来,你会越来越熟练的!
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
我想到的最简单的解决办法是:
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)
目标文件夹必须存在。