Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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
Python批量复制工具_Python_Python 3.x - Fatal编程技术网

Python批量复制工具

Python批量复制工具,python,python-3.x,Python,Python 3.x,我是一个3D艺术家。我对Python非常陌生,现在正在开发一个工具。 我的文件夹中有很多文件,子文件夹超过1000个。我必须根据我的.txt文件根据名称(而不是文件类型)复制特定文件。此文本文件包含我要复制的文件的名称列表 这里我有一个用于.txt文件读取代码的脚本: import os file = open("D:/Python/Test.txt", "r") print(file.read()) file.close() 这里我有复制文件的脚本: import shutil import

我是一个3D艺术家。我对Python非常陌生,现在正在开发一个工具。 我的文件夹中有很多文件,子文件夹超过1000个。我必须根据我的.txt文件根据名称(而不是文件类型)复制特定文件。此文本文件包含我要复制的文件的名称列表

这里我有一个用于.txt文件读取代码的脚本:

import os
file = open("D:/Python/Test.txt", "r")
print(file.read())
file.close()
这里我有复制文件的脚本:

import shutil
import os
dir1='D:/py_src_souce/'
dir2='E:/py_src_dst/'
for files in os.listdir(dir1):
    shutil.copy2(dir1 +files , dir2+files)
这两个文件单独运行都很好,但我不知道如何运行上面两个代码组合的脚本。
我想复制我在.txt文件中给出的文件名,该文件只复制到目标文件夹。谢谢你的阅读。如果有人能帮我解决这个问题,那将是我的救命稻草。

我的理解正确吗?你想从另一个脚本运行一个脚本?如果是这样,我使用
runpy

导入runpy
runpy.run\u路径(path\u name=“otherfile.py”)

否则,请参阅@jeremy_rutman的帖子。这是一个很好的例子。

我猜您想要将Test.txt中列出的所有文件从dir1复制到dir2

如果是这种情况,您可以:

import os
import shutil
with open("D:/Python/Test.txt", "r") as fp:
    files = fp.readlines()
    dir1='D:/py_src_souce/'
    dir2='E:/py_src_dst/'
    for file in files:
        file = file.replace('\n','')
        file1 = os.path.join(dir1,file)
        file2 = os.path.join(dir2,file)
        shutil.copy2(file1,file2) 
如果你想玩得更开心,你可以在尝试用os.path.exists(file1)复制文件之前检查文件是否存在于dir1中,并确保它不存在于dir2中


编辑-我添加了一行以删除Test.txt中的换行符。在粘贴的错误消息中,您可以在文件名的末尾看到一个
\n
(换行符),并且
\n
不是文件名的一部分-它的作用是在文本文件中保持行分隔

首先,学习如何正确地编写和分组它们-这两个概念是最基本的“代码重用”特性(脚本主要用于从模块调用函数)。嗨,jermy_rutman,谢谢你的回答。我运行你的脚本,但它不工作,我得到了一些错误,在这里我粘贴了什么得到错误,而运行脚本。。。。回溯(最后一次调用):文件“D:/Python/test/venv/read.py”,第10行,在shutil.copy2(文件1,文件2)文件“C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”,第432行,在copy2 copyfile(src,dst,follow\symlinks=follow\symlinks)文件“C:\Users\admin\AppData\Local\Programs\Python38-32\lib\shutil.py”,第261行,在copyfile中,open(src,'rb')作为fsrc,open(dst,'wb')作为fdst:OSError:[Errno 22]无效参数:“D:/py_src_souce/fox\n”进程已完成,退出代码为1Hi The Tech Robo,感谢您的回复。在我的txt文件中,有我要复制的文件的名称列表。