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

mal*_*ina 30 python directory move

我想使用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)
Run Code Online (Sandbox Code Playgroud)

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

Shi*_*ndi 50

试试这个..

import shutil
import os

source = '/path/to/source_folder'
dest1 = '/path/to/dest_folder'


files = os.listdir(source)

for f in files:
        shutil.move(source+f, dest1)
Run Code Online (Sandbox Code Playgroud)

  • 而不是连接字符串,最好使用`os.path.join()`方法 (7认同)
  • 注意:以上*将*递归地从源移动到目标.另外,在我的测试中,上面的代码在`source`和`dest1`中都缺少一个尾部斜杠. (4认同)

Dat*_*ice 14

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

此外,shutil 在 python 中更新,3.6以在此PEP-0519 中接受 pathlib 对象的更多详细信息

路径库

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.
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)


小智 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";
Run Code Online (Sandbox Code Playgroud)

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

for txt_file in glob.glob(src_fldr+"\\*.txt"):
    shutil.copy2(txt_file, dst_fldr);
Run Code Online (Sandbox Code Playgroud)


小智 5

请看一下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,因为如果destination参数指定了目录,则将使用srcname中的基本文件名将文件复制到dst中

更换COPY2举动