Moving all files from one directory to another using Python

前端 未结 9 1734
长发绾君心
长发绾君心 2020-12-24 00:57

I want to move all text files from one folder to another folder using Python. I found this code:

import os, shutil, glob

dst = \'/path/to/dir/Caches/com.app         


        
9条回答
  •  时光取名叫无心
    2020-12-24 01:40

    This should do the trick. Also read the documentation of the shutil module to choose the function that fits your needs (shutil.copy(), shutil.copy2(), shutil.copyfile() or shutil.move()).

    import glob, os, shutil
    
    source_dir = '/path/to/dir/with/files' #Path where your files are at the moment
    dst = '/path/to/dir/for/new/files' #Path you want to move your files to
    files = glob.iglob(os.path.join(source_dir, "*.txt"))
    for file in files:
        if os.path.isfile(file):
            shutil.copy2(file, dst)
    

提交回复
热议问题