Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用shutil在python中复制文件_Python_File_Shutil - Fatal编程技术网

使用shutil在python中复制文件

使用shutil在python中复制文件,python,file,shutil,Python,File,Shutil,目的是将收件箱文件夹下的所有txt文件复制到另一个文件夹中。 为此,我尝试了下面的代码 I have the following directory structure: -mailDir -folderA -sub1 -sub2 -inbox -1.txt -2.txt -89.txt -subInbox -

目的是将收件箱文件夹下的所有txt文件复制到另一个文件夹中。 为此,我尝试了下面的代码

I have the following directory structure:

 -mailDir
     -folderA
         -sub1
         -sub2
         -inbox
            -1.txt
            -2.txt
            -89.txt
            -subInbox
            -subInbox2
     -folderB
         -sub1
         -sub2
         -inbox
            -1.txt
            -2.txt
            -200.txt
            -577.txt
如果收件箱目录只有.txt文件,那么上面的代码可以正常工作。由于folderA目录下的收件箱文件夹有其他子目录以及.txt文件,因此代码返回“权限拒绝”错误。据我所知,shutil.copy不允许复制文件夹


目的是只将每个收件箱文件夹中的txt文件复制到其他位置。如果不同收件箱文件夹中的文件名相同,我必须保留这两个文件名。在这种情况下,我们如何改进代码?请注意,除了.txt以外,所有其他文件都是文件夹。

一个简单的解决方案是使用字符串方法筛选任何没有扩展名
.txt
i


这将忽略使用
os.listdir(ii)
找到的任何文件夹和非txt文件。我相信这就是您要寻找的。

一个简单的解决方案是使用string方法过滤任何没有
.txt
扩展名的
I


这将忽略使用
os.listdir(ii)
找到的任何文件夹和非txt文件。我相信这就是您要寻找的。

刚刚记得我曾经写过几个文件来解决这个问题。您可以找到源代码

简而言之,这里有两个有趣的功能:

  • 列出文件(loc,return\u dirs=False,return\u files=True,recursive=False,valid\u exts=None)
  • copy_文件(loc、dest、rename=False)
对于您的情况,您可以将这些函数复制并粘贴到项目中,并修改
copy\u文件
,如下所示:

import os
from os import path
import shutil

rootDir = "mailDir"
destDir = "destFolder"

eachInboxFolderPath = []
for root, dirs, files in os.walk(rootDir):
    for dirName in dirs:
        if(dirName=="inbox"):
            eachInboxFolderPath.append(root+"\\"+dirName)

for ii in eachInboxFolderPath:
    for i in os.listdir(ii):
         if i.endswith('.txt'):
            shutil.copy(path.join(ii,i),destDir)
那就这样说吧:

def copy_files(loc, dest, rename=False):
    # get files with full path
    files = list_files(loc, return_dirs=False, return_files=True, recursive=True, valid_exts=('.txt',))

    # copy files in list to dest
    for i, this_file in enumerate(files):
        # change name if renaming
        if rename:
            # replace slashes with hyphens to preserve unique name
            out_file = sub(r'^./', '', this_file)
            out_file = sub(r'\\|/', '-', out_file)
            out_file = join(dest, out_file)
            copy(this_file, out_file)
            files[i] = out_file
        else:
            copy(this_file, dest)

    return files

重命名方案可能不是您想要的,但至少不会覆盖您的文件。我相信这会解决你所有的问题。

刚刚记得我曾经写过几个文件来解决这个问题。您可以找到源代码

简而言之,这里有两个有趣的功能:

  • 列出文件(loc,return\u dirs=False,return\u files=True,recursive=False,valid\u exts=None)
  • copy_文件(loc、dest、rename=False)
对于您的情况,您可以将这些函数复制并粘贴到项目中,并修改
copy\u文件
,如下所示:

import os
from os import path
import shutil

rootDir = "mailDir"
destDir = "destFolder"

eachInboxFolderPath = []
for root, dirs, files in os.walk(rootDir):
    for dirName in dirs:
        if(dirName=="inbox"):
            eachInboxFolderPath.append(root+"\\"+dirName)

for ii in eachInboxFolderPath:
    for i in os.listdir(ii):
         if i.endswith('.txt'):
            shutil.copy(path.join(ii,i),destDir)
那就这样说吧:

def copy_files(loc, dest, rename=False):
    # get files with full path
    files = list_files(loc, return_dirs=False, return_files=True, recursive=True, valid_exts=('.txt',))

    # copy files in list to dest
    for i, this_file in enumerate(files):
        # change name if renaming
        if rename:
            # replace slashes with hyphens to preserve unique name
            out_file = sub(r'^./', '', this_file)
            out_file = sub(r'\\|/', '-', out_file)
            out_file = join(dest, out_file)
            copy(this_file, out_file)
            files[i] = out_file
        else:
            copy(this_file, dest)

    return files
重命名方案可能不是您想要的,但至少不会覆盖您的文件。我相信这会解决你所有的问题。

给你:

copy_files('mailDir', 'destFolder', rename=True)
导入操作系统
从操作系统导入路径
进口舒蒂尔
destDir=''
对于os.walk(os.getcwd())中的根目录、目录和文件:
#仅筛选出“.txt”文件。
files=[f表示文件中的f,如果f.endswith('.txt')]
#仅筛选出“收件箱”目录。
目录[:]=[d代表目录中的d,如果d=='inbox']
对于文件中的f:
p=路径连接(根,f)
#打印p
shutil.copy(p,destDir)
快速简单

对不起,我忘记了其中的部分,您还需要唯一的文件名。上述解决方案仅适用于单个收件箱文件夹中的不同文件名

要从多个收件箱复制文件并在目标文件夹中具有唯一名称,可以尝试以下操作:

import os
from os import path
import shutil

destDir = '<absolute-path>'
for root, dirs, files in os.walk(os.getcwd()):
    # Filter out only '.txt' files.
    files = [f for f in files if f.endswith('.txt')]
    # Filter out only 'inbox' directory.
    dirs[:] = [d for d in dirs if d == 'inbox']

for f in files:
    p = path.join(root, f)
    # print p
    shutil.copy(p, destDir)
导入操作系统
从操作系统导入路径
进口舒蒂尔
sourceDir=os.getcwd()
fixedLength=len(sourceDir)
destDir=''
filteredFiles=[]
对于os.walk(sourceDir)中的根目录、目录和文件:
#仅筛选出所有收件箱目录中的“.txt”文件。
如果root.endswith(“收件箱”):
#在这里,我将文件名加入到完整路径中,同时过滤txt文件
files=[如果f.endswith('.txt'),则文件中f的path.join(root,f)]
#将筛选的文件添加到主列表中
filteredFiles.extend(文件)
#创建文件路径和文件名的元组
filteredFiles=[(f,f[fixedLength+1:]。在filteredFiles中为f替换('/','-'))
对于过滤器文件中的(f,n):
打印“正在复制文件…”,f
#从路径复制到具有特定名称的dest目录
shutil.copy(f,path.join(destDir,n))
打印“复制”,str(len(filteredFiles)),“文件到”,destDir
如果您需要复制所有文件,而不仅仅是txt文件,则只需将条件
f.endswith('.txt')
更改为
os.path.isfile(f)
,同时过滤掉文件。

这里:

copy_files('mailDir', 'destFolder', rename=True)
导入操作系统
从操作系统导入路径
进口舒蒂尔
destDir=''
对于os.walk(os.getcwd())中的根目录、目录和文件:
#仅筛选出“.txt”文件。
files=[f表示文件中的f,如果f.endswith('.txt')]
#仅筛选出“收件箱”目录。
目录[:]=[d代表目录中的d,如果d=='inbox']
对于文件中的f:
p=路径连接(根,f)
#打印p
shutil.copy(p,destDir)
快速简单

对不起,我忘记了其中的部分,您还需要唯一的文件名。上述解决方案仅适用于单个收件箱文件夹中的不同文件名

要从多个收件箱复制文件并在目标文件夹中具有唯一名称,可以尝试以下操作:

import os
from os import path
import shutil

destDir = '<absolute-path>'
for root, dirs, files in os.walk(os.getcwd()):
    # Filter out only '.txt' files.
    files = [f for f in files if f.endswith('.txt')]
    # Filter out only 'inbox' directory.
    dirs[:] = [d for d in dirs if d == 'inbox']

for f in files:
    p = path.join(root, f)
    # print p
    shutil.copy(p, destDir)
导入操作系统
从操作系统导入路径
进口舒蒂尔
sourceDir=os.getcwd()
fixedLength=len(sourceDir)
destDir=''
filteredFiles=[]
对于os.walk(sourceDir)中的根目录、目录和文件:
#仅筛选出所有收件箱目录中的“.txt”文件。
如果root.endswith(“收件箱”):
#在这里,我将文件名加入到完整路径中,同时过滤txt文件
files=[如果f.endswith('.txt'),则文件中f的path.join(root,f)]
#将筛选的文件添加到主列表中
filteredFiles.extend(文件)
#创建文件路径和文件名的元组
filteredFiles=[(f,f[fixedLength+1:]。在filteredFiles中为f替换('/','-'))
对于过滤器文件中的(f,n):
打印“正在复制文件…”,f
#从路径复制到具有特定名称的dest目录
shutil.copy(f,path.join(destDir,n))
打印“已复制”,str(len(filteredFiles)),fi