简体   繁体   English

Python:根据文件名的一部分将文件移动到文件夹

[英]Python: Move files to folder based on Part of File name

Folder contains files文件夹包含文件

  1. filenameone_partone_1文件名one_partone_1
  2. filenameone_partone_2文件名one_partone_2
  3. filenameone_partone_3文件名one_partone_3
  4. filenameone_parttwo_1文件名one_parttwo_1
  5. filenameone_parttwo_2文件名one_parttwo_2
  6. filenametwo_1文件名two_1
  7. filenametwo_2文件名two_2

Now i want to move (1,2,3)(4,5)(6,7) to each folder.现在我想将 (1,2,3)(4,5)(6,7) 移动到每个文件夹。 Based on file name folder has to be created and respective files to be moved.必须根据文件名创建文件夹并移动相应的文件。 The following code works but file name it has in character range x:y but that will not works above file name examples.SO need some modification in file name pass.Thanks.以下代码有效,但文件名在字符范围 x:y 中,但在文件名示例上方不起作用。所以需要对文件名进行一些修改。谢谢。

     import os, shutil
        os.chdir("<abs path to desktop>")
        for f in os.listdir("folder"):
            folderName = f[0:10]
            if not os.path.exists(folderName):
                os.mkdir(folderName)
                shutil.copy(os.path.join('folder', f), folderName)
            else:
                shutil.copy(os.path.join('folder', f), folderName)

Assumption being file will always end with "_number"假设文件将始终以“_number”结尾

     import os, shutil
        os.chdir("<abs path to desktop>")
        for f in os.listdir("folder"):
            folderName = f[0:-2]
            if not os.path.exists(folderName):
                os.mkdir(folderName)
                shutil.copy(os.path.join('folder', f), folderName)
            else:
                shutil.copy(os.path.join('folder', f), folderName)




声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python:我可以将基于名称一部分的文件移动到具有该名称的文件夹中 - python: can i move a file based on part of the name to a folder with that name Python根据名称移动文件 - Python Move Files Based On Name 写一个 function 将两个同名文件(文件扩展名不同)移动到 python 同名文件夹中 - Writing a function to move two files with the same name (with different file extensions) to a folder with the same name in python 如何根据文件名称的一部分将文件移动到文件夹中? - How do I move files into folders based on a part of their name? 根据部分文件名合并文件 - Merge files based on part of file name Python 脚本根据文件扩展名移动文件 - Python script to move files based on file extension Python:如何将具有特定名称的文件移动到具有相同名称的文件夹中 - Python: how to move a file with a certain name to a folder with the same name Python:根据部分文件名和修改日期将文件从一个位置移动到另一个位置 - Python: Move files from one location to other based on partial file name and modified date 如何根据 pandas/csv 文件在同一行中移动文件和文件夹? - How to move files and folder in same rows based on a pandas/csv file? 将文件移动到恰好在Python中具有相同文件名的新文件夹中 - Move file to a new folder that happens to have the same file name in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM