使用Python将所有文件从一个目录移动到另一个目录

79

我想使用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 文件夹中的文件。 我没有收到错误信息,但也没有移动文件。

12个回答

148

试试这个:

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)

9
注意:上述代码将递归地从源目录移动文件到目标目录。另外,在我的测试中,上述代码在sourcedest1两个路径末尾都缺少斜杠。 - Dan Nissenbaum
这会将子目录(及其中的文件)移动到目标文件夹中吗? - daniel brandstetter
1
shutil.move(src, dst):递归地将文件或目录(src)移动到另一个位置(dst)。 - mcmayer
你需要在路径'source'和'dest1'的末尾加上'/'。 另外,为了更加安全,应该将shutil.move(source+f, dest1)改为shutil.move(source+f, dest1+f)。否则,整个source+f都会成为一个名为dest1的文件。 - Tom
总之,如果你想要移动子目录,那么使用以下代码:for f in files: shutil.move(os.path.join(source, f), os.path.join(dest1,f)) - Deskjokey

23
惊讶的是,这里没有使用Python 3.4中引入的pathlib来回答问题。
此外,Python 3.6中更新了shutil,可以接受pathlib对象。更多细节请参考PEP-0519

Pathlib(移动文件,不复制)

from pathlib import Path

src_path = Path('/tmp').joinpath('files_to_move')
# ^ the same as /tmp/files_to_move
#   OR //tmp//files_to_move if on windows. 

for each_file in src_path.glob('*.*'): # grabs all files
    trg_path = src_path.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 = Path('/tmp').joinpath('files_to_move')
trg_path = src_path.parent # this would be '/tmp/' from the above example.

for src_file in src_path.glob('*.*'):
    shutil.copy(src_file, trg_path)

之前(两个例子)

enter image description here

移动示例后

enter image description here

复制示例后

enter image description here


1
谢谢,这正是我所寻找的! - edo101
1
我认为你的意思是要执行 Path(src_path).glob('*.*'),对吗? - emmagras
Path 还实现了一个名为 iterdir 的方法,以防您不想使用 .glob('*.*')。https://docs.python.org/3/library/pathlib.html#pathlib.Path.iterdir - emmagras
@emmagras 很好的发现,下次请随意编辑 :) 您还可以使用“rglob”来遍历目录结构。 - Umar.H

8
请看这个实现了copytree函数的例子: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,因为如果目标参数指定一个目录,则文件将被复制到dst中,并使用srcname的基本文件名。

copy2替换为move


6

将“.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);

4
这应该能解决问题。此外,请阅读shutil模块的文档,选择适合你需求的函数(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文件的目标位置? - malina

4
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

每小时运行一次!干杯


2

试试这个:

 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))

1
使用 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)

0

这个脚本在目录中查找Docx文件,并创建一个文件夹来存放这些文件,然后将它们移动到创建的文件夹中。

import os
import glob
import shutil

docfiles=glob.glob("./**/*.docx" , recursive=True)
if docfiles:
    docdir = os.path.join("./DOCX")
    os.makedirs(docdir , exist_ok = True)
    for docfile in docfiles:
        if docfile in docdir:
            pass
        else:
            shutil.move(os.path.join(docfile),docdir)
            print("Files Moved")

0
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")

3
仅有代码转储而没有任何解释很少有帮助。Stack Overflow 是关于学习的,而不是提供盲目复制和粘贴的片段。请[编辑]您的问题并解释它如何比 OP 提供的更好。请参见[答案]。 - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接