Python将文件从符合给定条件的目录移动到新目录 [英] Python move files from directories that match given criteria to new directory

查看:180
本文介绍了Python将文件从符合给定条件的目录移动到新目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a directory that looks something like this:

.
├── 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是带编号的作业文件夹之一.

I want to move all the files inside the hwN folders into homework. Example homework will contain hw1.pdf -> hw13.pdf and not keep any of the folders named hwN Where N is one of the numbered homework folders.

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

I have a python script that is very nearly working:

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)

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

However, the commented out code which I am trying to use to move just the files not the folders results in this error:

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问题,实际上有一种更简便的方法请指出我的方向.另外,是的,我意识到我花了很多时间进行调试和编写代码,因此可以很容易地手工完成,但这不是重点.

To summarize, how can I move all the files contained in hw1, hw2, etc. to ./homework without moving the folders themselves? If this is xy problem and there is in fact an easier way to do this please point me in that direction. Also yes I realize that in the amount of time I've spent debugging and writing this I could easily have done it by hand, but that isn't the point.

谢谢.

推荐答案

您快到了.当您进入shutil.move(eachFile,source)时,此处的"eachFile"仅是您想要的文件的名称.例如,"hw13.pdf".因此它将尝试在根路径中搜索它,但是在根中没有"hw13.pdf"(正如异常"消息所指出的那样).

You're almost there. When you get to shutil.move(eachFile, source), 'eachFile' here is only the name of the file you want. For example, 'hw13.pdf'. So it will try to search for it in the root path, but there is no 'hw13.pdf' in the root (as the Exception message points out).

您需要做的只是将您所在文件夹的名称与您要移动的文件的名称连接起来:

What you need to do is just join the name of the folder you're in to the name of the file you want to move:

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)

这篇关于Python将文件从符合给定条件的目录移动到新目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆