Python 将文件从符合给定条件的目录移动到新目录

Python move files from directories that match given criteria to new directory

我有一个看起来像这样的目录:

.
├── files.py
├── homework
├── hw1
│   └── hw1.pdf
├── hw10
│   └── hw10.pdf
├── hw13
│   └── hw13.pdf
├── hw2
│   └── hw2.pdf
├── hw3
│   └── hw3.pdf
├── hw4
│   └── hw4.pdf
├── hw7
│   └── hw7.pdf
├── IntroductionToAlgorithms.pdf
├── p157
│   └── Makefile
├── p164
│   └── project
├── p171
│   ├── project
├── p18
│   └── project
├── p246
│   ├── project
├── p257
│   ├── project
├── p307
│   ├── project
├── p34
│   └── project
├── p363
│   ├── project
├── p431
│   ├── bit_buffer.h
├── p565
│   ├── project
├── p72
│   └── project
├── README.md
└── tree.txt

我想将 hwN 文件夹中的所有文件移动到作业中。 示例作业将包含 hw1.pdf -> hw13.pdf 并且不保留任何名为 hwN 的文件夹 其中 N 是编号的作业文件夹之一。

我有一个几乎可以正常工作的 python 脚本:

files.py:

import os
import shutil

if not os.path.exists("homework"):
    os.makedirs("homework")
    print("created hw directory")

source='/home/kalenpw/Documents/School/2017Spring/CS3385/homework/'

files = os.listdir()

for f in files:
    if f.startswith("hw") and len(f) > 2:
        #This line works but it keeps the subfolders where I want the files directly in ./homework
        shutil.move(f, source)
#        for eachFile in os.listdir(f):
#           #Ideally this would move all the files within the hw folders and move just the file not the folder to my source
#            shutil.move(eachFile, source)

但是,我试图用来移动文件而不是文件夹的注释掉的代码导致了这个错误:

Traceback (most recent call last):
  File "/usr/lib/python3.5/shutil.py", line 538, in move
    os.rename(src, real_dst)
FileNotFoundError: [Errno 2] No such file or directory: 'hw13.pdf' -> '/home/kalenpw/Documents/School/2017Spring/CS3385/homework/hw13.pdf'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "files.py", line 17, in <module>
    shutil.move(eachFile, source)
  File "/usr/lib/python3.5/shutil.py", line 552, in move
    copy_function(src, real_dst)
  File "/usr/lib/python3.5/shutil.py", line 251, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "/usr/lib/python3.5/shutil.py", line 114, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'hw13.pdf'

总而言之,如何在不移动文件夹本身的情况下将 hw1、hw2 等中包含的所有文件移动到 ./homework?如果这是 xy problem 并且实际上有更简单的方法可以做到这一点,请指出那个方向。另外,是的,我意识到在我调试和编写这篇文章的过程中,我可以很容易地手工完成,但这不是重点。

谢谢。

试试这个:

from os import walk, path

source='/home/kalenpw/Documents/School/2017Spring/CS3385/homework/'

for (dirpath, dirnames, filenames) in walk(source):
    for file in filenames:
        shutil.move(path.join(dirpath,file), source)

你快到了。当你到shutil.move(eachFile, source)时,这里的'eachFile'只是你要的文件名。例如,'hw13.pdf'。因此它将尝试在根路径中搜索它,但根路径中没有 'hw13.pdf'(如异常消息指出的那样)。

您需要做的只是将您所在文件夹的名称加入您要移动的文件的名称:

for f in files:
    if f.startswith("hw") and len(f) > 2:
        for eachFile in os.listdir(f):
            filePath = os.path.join(f, eachFile)
            shutil.move(filePath, source)