简体   繁体   中英

How to organize files in Python?

I have PDF files likes this:

  • 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 .

I have many files. I had used 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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