Moving all files from one directory to another using Python

前端 未结 9 1653
长发绾君心
长发绾君心 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:29

    Move files with filter( using Path, os,shutil modules):

    from pathlib import Path
    import shutil
    import os
    
    src_path ='/media/shakil/New Volume/python/src'
    trg_path ='/media/shakil/New Volume/python/trg'
    
    for src_file in Path(src_path).glob('*.txt*'):
        shutil.move(os.path.join(src_path,src_file),trg_path)
    
    0 讨论(0)
  • 2020-12-24 01:40

    Copying the ".txt" file from one folder to another is very simple and question contains the logic. Only missing part is substituting with right information as below:

    import os, shutil, glob
    
    src_fldr = r"Source Folder/Directory path"; ## Edit this
    
    dst_fldr = "Destiantion Folder/Directory path"; ## Edit this
    
    try:
      os.makedirs(dst_fldr); ## it creates the destination folder
    except:
      print "Folder already exist or some error";
    

    below lines of code will copy the file with *.txt extension files from src_fldr to dst_fldr

    for txt_file in glob.glob(src_fldr+"\\*.txt"):
        shutil.copy2(txt_file, dst_fldr);
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题