首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python -将列表中的特定文件复制到新文件夹中

Python -将列表中的特定文件复制到新文件夹中
EN

Stack Overflow用户
提问于 2018-07-26 05:42:31
回答 3查看 9.8K关注 0票数 2

我正在尝试让我的程序从一个文件(例如.txt)中读取一个名称列表,然后在一个选定的文件夹中搜索这些文件,并将这些文件复制并粘贴到另一个选定的文件夹中。我的程序运行时没有错误,但没有执行任何操作:

代码-更新:

代码语言:javascript
复制
import os, shutil
from tkinter import filedialog
from tkinter import *


root = Tk()
root.withdraw()

filePath = filedialog.askopenfilename()
folderPath = filedialog.askdirectory()
destination = filedialog.askdirectory()

filesToFind = []
with open(filePath, "r") as fh:
    for row in fh:
        filesToFind.append(row.strip())

#Added the print statements below to check that things were feeding correctly
print(filesToFind)
print(folderPath)
print(destination)

#The issue seems to be with the copy loop below:    
for target in folderPath:
    if target in filesToFind:
        name = os.path.join(folderPath,target)
        print(name)
        if os.path.isfile(name):
            shutil.copy(name, destination)
        else:
            print ("file does not exist", name)
        print(name)

更新-运行时没有错误,但不移动任何文件。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-08-01 04:53:03

有效的代码-

代码语言:javascript
复制
import os
import shutil
from tkinter import *
from tkinter import filedialog

root = Tk()
root.withdraw()

filePath = filedialog.askopenfilename()
folderPath = filedialog.askdirectory()
destination = filedialog.askdirectory()

# First, create a list and populate it with the files

# you want to find (1 file per row in myfiles.txt)

filesToFind = []
with open(filePath, "r") as fh:
    for row in fh:
        filesToFind.append(row.strip())

# Had an issue here but needed to define and then reference the filename variable itself
for filename in os.listdir(folderPath):
    if filename in filesToFind:
        filename = os.path.join(folderPath, filename)
        shutil.copy(filename, destination)
    else:
        print("file does not exist: filename")

注意-需要在正在读取的文件中包含文件扩展名。感谢@lenik和@John Gordon的帮助!是时候对其进行改进,使其更加用户友好

票数 1
EN

Stack Overflow用户

发布于 2018-07-26 08:06:09

你程序的最后一部分可能会工作得更好:

代码语言:javascript
复制
for file in files:
    if file in filesToFind:
        name = os.path.join( folderPath, file )
        if os.path.isfile( name ) :
            shutil.copy( name, destination)
        else :
            print 'file does not exist', name

否则,你很难知道你从哪里复制你的文件,可能是当前文件夹,如果你不使用folderPath,为什么你需要之前输入它。

顺便说一句,file是python中的保留字,我建议您的变量使用其他名称,这与python保留字不一致。

票数 1
EN

Stack Overflow用户

发布于 2018-07-26 10:49:53

你的最后一个部分有一个问题。

代码语言:javascript
复制
for file in os.listdir(folderPath): 
    for file in files:
        if file in filesToFind:
            shutil.copy(file, destination)

第一个for循环遍历目录中的每个文件名,这是完全可以理解的。

第二个for是错误的,因为files不存在。你打算让它做什么?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51528103

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档