简体   繁体   English

如何用Python组织文件?

[英]How to organize files in Python?

I have PDF files likes this: 我有这样的PDF文件:

  • 9706_s15_qp_12
  • 9706_w15_qp_12

I want to move files based on their names. 我想根据文件名移动文件。 Like _s15 to summer 2015 and _w15 to winter 2015 . 就像_s15summer 2015_w15winter 2015

I have many files. 我有很多文件。 I had used shutil.move('C:\\\\bacon.txt', 'C:\\\\eggs') 我用过shutil.move('C:\\\\bacon.txt', 'C:\\\\eggs')

But the problem is I have to write file names one by one. 但是问题是我必须一个接一个地写文件名。 How to do it recursively? 如何递归执行?

I used this code: 我使用以下代码:

import os
import shutil

os.chdir('D:\\Accounting (9706)')
for root, dirs, files in os.walk('D:\\Accounting (9706)', topdown=False):
    for name in files:
        shutil.move(name, 'D:\\')

and it moved all of my files. 它移动了我所有的文件。 I want to move specific ones. 我想移动特定的。

Maybe try making a dictionary where the key is the location where you wish to move the file to and the value is a list of all of the files which you wish to move to that location. 也许尝试制作一个字典,其中的键是您希望将文件移动到的位置,而值是您希望移动到该位置的所有文件的列表。 Then traverse the dictionary's keys and values. 然后遍历字典的键和值。 you can use the move utility with variables, so long as the variables are strings and correspond to a valid location. 您可以将move实用程序与变量一起使用,只要变量是字符串并且对应于有效位置即可。

Try this: 尝试这个:

import os
for root, dirs, files in os.walk('your source path', topdown=False):
        for name in files:
            shutil.move(name, 'your target path')

That's what you're looking for I believe: 我相信您正在寻找的是:

import os
import shutil
moving_dict = {
    "_w15": "D:\\Winter 15\\",
    "_s15": "D:\\Summer 15\\"
}

os.chdir('D:\\Accounting (9706)')
for root, dirs, files in os.walk('D:\\Accounting (9706)', topdown=False):
    for name in files:
        for short, dest in moving_dict.items():
            if short in name:
                shutil.move(name, dest)
                break

        else:
            print("Short name wasn't found in "+name)

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

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