python拷贝文件到指定路径不存在,Python-将列表中的特定文件复制到新文件夹中...

本文探讨了一位开发者如何使用Python从txt文件读取名字列表,在选定文件夹中搜索并复制文件到另一个目标目录的过程。起初代码存在问题,通过更新后,解决了如何正确匹配文件名并进行复制的问题。作者强调了包括文件扩展名的重要性,并感谢了Lenik和John Gordon的帮助。
摘要由CSDN通过智能技术生成

I am trying to get my program to read a list of names from a file (say .txt), then search for those in a selected folder and copy and paste those files to another selected folder. My program runs without errors but does not do anything:

Code - updated:

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)

Update - runs without errors but does not move any files.

解决方案

Code that works -

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

Note - Need to included the file extension in the file being read. Thanks to @lenik and @John Gordon for the help getting there! Time to refine it to make it more userfriendly

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值