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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41826868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:41:27  来源:igfitidea点击:

Moving all files from one directory to another using Python

pythondirectorymove

提问by malina

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

我想使用 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)

I would want it to move all the files in the Blobfolder. I am not getting an error, but it is also not moving the files.

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

回答by Shivkumar kondi

Try this:

尝试这个:

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)

回答by Rachel M. Carmena

Please, take a look at implementation of the copytreefunction which:

请看一下copytree函数的实现:

  • List directory files with:

    names = os.listdir(src)

  • Copy files with:

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

  • 列出目录文件:

    names = os.listdir(src)

  • 复制文件:

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

Getting dstnameis not necessary, because if destination parameter specifies a directory, the file will be copied into dstusing the base filename from srcname.

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

Replace copy2by move.

更换COPY2举动

回答by ToUsIf

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:

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

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

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

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

回答by Byakko_Haku

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

这应该可以解决问题。另请阅读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)

回答by Daniel Adenew

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

A little bit cooked code with log feature. You can also configure this to run at some period of time using crontab.

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

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

runs every hour! cheers

每小时运行一次!干杯

回答by Datanovice

suprised this doesn't have an answer using pathilib which was introduced in python 3.4+

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

additionally, shutil updated in python 3.6to accept a pathlib object more details in this PEP-0519

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

Pathlib

路径库

from pathlib import Path

src_path = '\tmp\files_to_move'

for each_file in 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 to copy files.

Pathlib 和shutil 来复制文件。

from pathlib import Path
import shutil

src_path = '\tmp\files_to_move\'
trg_path = '\tmp\'

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