简体   繁体   English

将文件移出文件夹 Python

[英]Move Files out of Folders Python

I save a lot of content into a directory Q:\Move_Folder我把很多内容保存到一个目录 Q:\Move_Folder

Sometimes that content will be saved directly, such as Q:\Move_Folder\video.mkv有时会直接保存那个内容,比如Q:\Move_Folder\video.mkv

Most of the time it is saved automatically as this: Q:\Move_Folder\Subfolder\video.mkv大多数时候它会自动保存为:Q:\Move_Folder\Subfolder\video.mkv

I am looking to iterate through every subfolder inside of Move_Folder, extract anything that ends with a certain file extension, and move it out of the folder, so that it is Q:\Move_Folder\video.mkv我希望遍历 Move_Folder 中的每个子文件夹,提取以特定文件扩展名结尾的所有内容,然后将其移出文件夹,这样它就是 Q:\Move_Folder\video.mkv

I have run this script and it works when moving from say Q:\Completed to Q:\Move_Folder, and will move all correct file extensions, but when doing it from within Q:\Move_Folder I am currently returned no error, but no files are moved either:我已经运行了这个脚本,它在从 Q:\Completed 移动到 Q:\Move_Folder 时有效,并且会移动所有正确的文件扩展名,但是当从 Q:\Move_Folder 中执行时,我目前没有返回任何错误,但没有文件被移动:

Code:代码:

import os
import os.path
import shutil

target = r'Q:\Move_Folder'

ext = ['.mkv', '.mp4','.avi','.srt','.ass']
movedFiles = []

from pathlib import Path
rootdir = Path(r"Q:\Move_Folder")
os.path.isfile(rootdir)


for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if rootdir.is_dir():
            pass
        else:
            file.endswith(tuple(ext))
            movedFiles.append(file)
            fullfile = os.path.join(subdir, file)
            shutil.move(fullfile, target)
            print("FileMoved: " + file)

Going to add the final product below if anyone has any similar type of need, I think this is quite useful.如果有人有任何类似的需求,将在下面添加最终产品,我认为这非常有用。 Tested it, and it works for what I want.对其进行了测试,它适用于我想要的。

import os
import os.path
import shutil

from pathlib import Path

# Setting all variables
target = r'Q:\Move_Folder'
deletedFiles = []
# If you don't have .r00-.r09 here they will not be deleted, because numbers do not
# increment as 00-09 they increment as 0-9
r = ['.r00', '.r01', '.r02', '.r03', '.r04', '.r05', '.r06', '.r07', '.r08', '.r09']
ext2 = ['.nfo', '.jpg', '.rar', '.jpg', '.png', '.sfv', '.NFO']
rootdirss = r"Q:\Move_Folder"
x = 00
ext = ('.mkv', '.mp4','.avi','.srt','.ass')
movedFiles = []
rootdir = Path(target)

# Search for Files that I want to keep, and move them to Move_Folder out of their pre-existing folder
for file in rootdir.rglob("*"):
    if file.name.endswith(ext) and file.parent != rootdir:
        print(file.parent)
        movedFiles.append(file)
        file.rename(rootdir / file.name)
        print("File Moved To Move_Folder: " + file.name)

# Iterate through x which is for .r00 files, adding them 
# to .r00 through .r150 for deleting purposes.
while x < 150:
    r.append(".r" + str(x))
    x += 1

# Main content for deleting junk, will first iterate through ext for normal file extensions
# Then will iterate through .r00 files and deleting them
for subdir, dirs, files in os.walk(rootdirss):
    for file in files:
        if file.endswith(tuple(ext2)):
            deletedFiles.append(file)
            os.remove(os.path.join(subdir, file))
            print("Deleted: " + file)
        # Begin of deleting .r00 files    
        for i in r:
            if file.endswith(i):
                deletedFiles.append(file)
                os.remove(os.path.join(subdir, file))
                print("Deleted: " + file)        

# Search for any directories (Folders), and delete them
for dir in rootdir.rglob('*'):
    if dir.name.endswith(ext):
        pass
    else:
        print("Deleting Folder: ", dir)
        shutil.rmtree(dir)

You've already made the first good step of using pathlib , why not go all the way?您已经迈出了使用pathlib的第一步,为什么不一路使用 go 呢? See how simple it is:看看它有多简单:

from pathlib import Path

target = r'Q:\Move_Folder'

ext = ('.mkv', '.mp4','.avi','.srt','.ass')
movedFiles = []

rootdir = Path(target)

for file in rootdir.rglob("*"):
    if file.name.endswith(ext) and file.parent != rootdir:
        movedFiles.append(file)
        file.rename(rootdir / file.name)
        print("FileMoved: " + file.name)

pathlib is very useful and powerful when working with paths. pathlib在处理路径时非常有用和强大。 In most use-cases I came across it was much more simple than using os.path equivalents and it is much more platform-safe.在我遇到的大多数用例中,它比使用os.path等价物简单得多,而且平台安全得多。

The first issue here is that rootdir.is_dir() will always be true since Q:Move_Folder is a directory and the value for rootdir is never mutated.这里的第一个问题是rootdir.is_dir()将始终为真,因为Q:Move_Folder是一个目录并且rootdir的值永远不会发生变化。

You also seem to cast ext to a tuple when you should probably make it a tuple for the get-go unless you need to be able to add more extensions at runtime.除非您需要能够在运行时添加更多扩展,否则您似乎也将ext转换为一个元组,而您可能应该将它作为一开始的元组。

Additionally you aren't doing anything with the return type of file.endswith(tuple(ext))此外,您没有对file.endswith(tuple(ext))的返回类型做任何事情

You could probably simplify this into:您可能可以将其简化为:

for root, dirs, files, os.walk(rootdir):
    for file in files:
        if file.endswith(tuple(ext)):
            shutil.move(os.path.join(root, name), target)
            print("FileMoved: " + file)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM