python根据文件名中的文本字符将多个文件从一个文件夹移动到另一个文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25070614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:41:29  来源:igfitidea点击:

python moving multiple files from one folder to the other based on text characters in file name

pythonpython-2.7

提问by user197240

I'm quite new to Python. I've been exploring the shutilmodule and can move things in general. My question revolves around:

我对Python陌生。我一直在探索这个shutil模块并且可以移动一般的东西。我的问题围绕:

Imagine a scenario in which you have hundreds of files in an export folder. While all the files are distinct, 13 of each are for a specific vendor. I would like to create a script that goes through the export folder, evaluates each file name, grabs all the Apple files and puts them in the Apple Folder, Intel files and puts them in the Intel Folder, etc. Any wisdom would be greatly appreciated.

想象一个场景,其中导出文件夹中有数百个文件。虽然所有文件都是不同的,但每个文件中有 13 个是针对特定供应商的。我想创建一个脚本,通过导出文件夹,评估每个文件名,抓取所有 Apple 文件并将它们放入 Apple 文件夹,Intel 文件并将它们放入 Intel 文件夹等。任何智慧将不胜感激.

I was trying to have wildcards in the shutilcopy, but did not have any luck.

我试图在shutil副本中使用通配符,但没有任何运气。

Thanks,

谢谢,

JT

JT

回答by user1893148

Assuming there are specific strings in the file names that identify which vendor the report relates to, you could create a dictionary that maps those identifying-strings to the appropriate vendor. For example:

假设文件名中有特定字符串标识报告与哪个供应商相关,您可以创建一个字典,将这些标识字符串映射到适当的供应商。例如:

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

This will create a folder in the current directory, named for the appropriate vendor, and copy that vendor's reports there. Note that this example uses the s.lower()method so that it won't matter whether the vendor name is capitalized.

这将在当前目录中创建一个以适当供应商命名的文件夹,并将该供应商的报告复制到那里。请注意,此示例使用s.lower()方法,因此供应商名称是否大写无关紧要。

回答by Padraic Cunningham

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

回答by Andreas Myriounis

Easiest solution I could think of:

我能想到的最简单的解决方案:

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)

The destination folders doneed to exist.

目标文件夹确实需要存在。

回答by Andreas Myriounis

Andreas's answer is fine for the Apples example you've given. If you're looking for something more meaty, check out regexs. They let you search for repeating patterns of text.

Andreas 的回答适用于您给出的 Apples 示例。如果您正在寻找更丰富的东西,请查看正则表达式。它们让您搜索重复的文本模式。

Where I work, for example, we have different formats of text depending on whether the file is a report, or a technical drawing etc. They all follow a format similar to "company initials/project number/department.

例如,在我工作的地方,根据文件是报告还是技术图纸等,我们有不同的文本格式。它们都遵循类似于“公司缩写/项目编号/部门”的格式。

As a regex, you could search something like:

作为正则表达式,您可以搜索以下内容:

import re

fileregex = re.compile(r'(\w\w)/(\d{4})/(\w\w))
for file in os.listdir(*path*):
    filename = fileregex.search(file)

It's a handy tool to know.

这是一个方便的工具。

回答by grambo

Minor edit on Padaic's answer:

对 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])

回答by ray1195

The code below is working for me -

下面的代码对我有用-

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)