【问题标题】:Moving all files from one directory to another using Python使用 Python 将所有文件从一个目录移动到另一个目录
【发布时间】:2025-12-25 01:45:11
【问题描述】:

我想使用 Python 将所有文本文件从一个文件夹移动到另一个文件夹。我找到了这段代码:

import os, shutil, glob

dst = '/path/to/dir/Caches/com.apple.Safari/WebKitCache/Version\ 4/Blobs '
try:
    os.makedirs(/path/to/dir/Tumblr/Uploads) # create destination directory, if needed (similar to mkdir -p)
except OSError:
    # The directory already existed, nothing to do
    pass

for txt_file in glob.iglob('*.txt'):
    shutil.copy2(txt_file, dst)

我希望它移动Blob 文件夹中的所有文件。我没有收到错误,但它也没有移动文件。

【问题讨论】:

    标签: python directory move


    【解决方案1】:

    这应该可以解决问题。另请阅读 shutil 模块的documentation 以选择适合您需要的函数(shutil.copy()、shutil.copy2()、shutil.copyfile() 或 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)
    

    【讨论】:

    • 但是我在哪里定义 txt 文件的新目的地?
    【解决方案2】:

    试试这个:

    import shutil
    import os
        
    source_dir = '/path/to/source_folder'
    target_dir = '/path/to/dest_folder'
        
    file_names = os.listdir(source_dir)
        
    for file_name in file_names:
        shutil.move(os.path.join(source_dir, file_name), target_dir)
    

    【讨论】:

    • 注意:上述递归地将文件从源移动到目标。此外,在我的测试中,上述代码在sourcedest1 中都缺少斜杠。
    • 这会将子目录(和/或其中的文件)移动到目标文件夹中吗?
    • @danielbrandstetter shutil.move(src, dst):递归地将文件或目录 (src) 移动到另一个位置 (dst)。
    • 您需要在路径 sroucedest1 的末尾添加“/”。另外shutil.move(source+f, dest1) 这应该是shutil.move(source+f, dest1+f) 以更加安全。否则所有的source+f 都会变成一个路径为dest1的文件
    • 总之,如果你想移动子目录,使用:for f in files: shutil.move(os.path.join(source, f), os.path.join(dest1, f))
    【解决方案3】:

    请看一下copytree函数的实现:

    • 列出目录文件:

      names = os.listdir(src)

    • 复制文件:

    for name in names:
      srcname = os.path.join(src, name)
      dstname = os.path.join(dst, name)
      copy2(srcname, dstname)
    

    获取 dstname 不是必需的,因为如果目标参数指定一个目录,文件将使用 srcname中的基本文件名复制到 dst >.

    copy2 替换为 move

    【讨论】:

      【解决方案4】:

      将“.txt”文件从一个文件夹复制到另一个文件夹非常简单,问题包含逻辑。只有缺失的部分用正确的信息替换如下:

      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";
      

      以下代码行将复制带有 *.txt 扩展名的文件 src_fldr 到 dst_fldr

      for txt_file in glob.glob(src_fldr+"\\*.txt"):
          shutil.copy2(txt_file, dst_fldr);
      

      【讨论】:

        【解决方案5】:
        import shutil 
        import os 
        import logging
        
        source = '/var/spools/asterisk/monitor' 
        dest1 = '/tmp/'
        
        
        files = os.listdir(source)
        
        for f in files:
                shutil.move(source+f, dest1)
        
        logging.basicConfig(filename='app.log', filemode='w', format='%(name)s
        - %(levelname)s - %(message)s')
        
        logging.info('directories moved')
        

        带有日志功能的一些熟代码。您还可以使用 crontab 将其配置为在某个时间段运行。

        * */1 * * * python /home/yourprogram.py > /dev/null 2>&1
        

        每小时运行一次!干杯

        【讨论】:

          【解决方案6】:

          很惊讶这没有使用在 python 3.4+ 中引入的 pathilib 的答案

          此外,shutil 在 python 3.6 中进行了更新,以接受 pathlib 对象,更多详细信息请参见 PEP-0519

          路径库

          from pathlib import Path
          
          src_path = '\tmp\files_to_move'
          
          for each_file in Path(src_path).glob('*.*'): # grabs all files
              trg_path = each_file.parent.parent # gets the parent of the folder 
              each_file.rename(trg_path.joinpath(each_file.name)) # moves to parent folder.
          

          Pathlib & shutil 复制文件。

          from pathlib import Path
          import shutil
          
          src_path = '\tmp\files_to_move'
          trg_path = '\tmp'
          
          for src_file in Path(src_path).glob('*.*'):
              shutil.copy(src_file, trg_path)
          

          【讨论】:

          • 谢谢,这正是我要找的!
          • 我想你的意思是在这里做Path(src_path).glob('*.*')?
          • Path 还实现了一个名为iterdir 的方法,以防你不想.glob('*.*') docs.python.org/3/library/pathlib.html#pathlib.Path.iterdir
          • @emmagras 不错,下次随时编辑 :) 你还有rglob 来搜索目录结构。
          【解决方案7】:

          例如,如果我想将所有 .txt 文件从一个位置移动到另一个位置(例如在 Windows 操作系统上),我会这样做:

          import shutil
          import os,glob
          
          inpath = 'R:/demo/in' 
          outpath = 'R:/demo/out'
          
          os.chdir(inpath)
          for file in glob.glob("*.txt"):
          
              shutil.move(inpath+'/'+file,outpath)
          

          【讨论】:

            【解决方案8】:
            def copy_myfile_dirOne_to_dirSec(src, dest, ext): 
            
                if not os.path.exists(dest):    # if dest dir is not there then we create here
                    os.makedirs(dest);
                    
                for item in os.listdir(src):
                    if item.endswith(ext):
                        s = os.path.join(src, item);
                        fd = open(s, 'r');
                        data = fd.read();
                        fd.close();
                        
                        fname = str(item); #just taking file name to make this name file is destination dir     
                        
                        d = os.path.join(dest, fname);
                        fd = open(d, 'w');
                        fd.write(data);
                        fd.close();
                
                print("Files are copyed successfully")
            

            【讨论】:

            • 没有任何解释的代码转储很少有帮助。 Stack Overflow 是关于学习的,而不是提供 sn-ps 来盲目复制和粘贴。请edit您的问题并解释它如何比 OP 提供的更好。见How to Answer
            【解决方案9】:

            使用过滤器移动文件(使用 Path、os、shutil 模块):

            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)
            

            【讨论】:

              【解决方案10】:

              试试这个:

               if os.path.exists(source_dir):
                  try:
                      file_names = os.listdir(source_dir)
                      if not os.path.exists(target_dir):
                          os.makedirs(target_dir)
                      for file_name in file_names:
                          shutil.move(os.path.join(source_dir, file_name), target_dir)
                  except OSError as e:
                      print("Error: %s - %s." % (e.filename, e.strerror))
              else:
                  log.debug(" Directory not exist {}".format(source_dir))
              

              【讨论】:

                最近更新 更多